Working with Arrays in Bash

By Anurag Singh

Updated on Dec 26, 2024

Working with Arrays in Bash

In this tutorial, we're working with arrays in bash.

Bash arrays are powerful data structures that allow you to store and manipulate collections of values within a script. They can simplify tasks like data processing, managing configurations, and automating repetitive operations. How to create, access, and iterate over arrays in Bash, providing detailed examples and explanations.

Prerequisites

Before getting started, ensure you have the following:

  • A KVM VPS or dedicated server with any Linux distro installed.
  • A non-root user with sudo privileges.
  • Basic knowledge of Linux commands.

Working with Arrays in Bash

Creating Arrays in Bash

Indexed Arrays

An indexed array stores elements accessed by numerical indices. You can define an indexed array explicitly or implicitly.

# Explicit definition
my_array=(value1 value2 value3)

# Adding values later
my_array[3]=value4

Each element in an indexed array is stored in a specific position, starting from index 0. Values can include strings, numbers, or any data type supported by Bash.

Associative Arrays

An associative array uses keys instead of numeric indices. This feature requires Bash version 4.0 or later.

declare -A my_assoc_array
my_assoc_array[key1]=value1
my_assoc_array[key2]=value2

Associative arrays are useful for creating dictionaries, allowing for descriptive keys and enhanced readability.

Accessing Array Elements

Indexed Arrays

Access elements in an indexed array using their numerical index within square brackets.

echo "${my_array[0]}"  # Outputs: value1
echo "${my_array[3]}"  # Outputs: value4

If an index is out of range, Bash returns an empty value without error, making bounds-checking important.

Associative Arrays

Access elements in an associative array using their key names.

echo "${my_assoc_array[key1]}"  # Outputs: value1
echo "${my_assoc_array[key2]}"  # Outputs: value2

Accessing a nonexistent key will return an empty value.

Iterating Over Arrays

Indexed Arrays

You can iterate through all the elements of an indexed array using a for loop.

for value in "${my_array[@]}"; do
  echo "$value"
done

Using ${my_array[@]} ensures all elements are retrieved as separate items, even if they contain spaces.

Associative Arrays

Iterate over the keys or values in an associative array using a for loop.

for key in "${!my_assoc_array[@]}"; do
  echo "$key: ${my_assoc_array[$key]}"
done

${!my_assoc_array[@]} retrieves all keys, allowing you to access corresponding values within the loop.

Advanced Array Operations

Appending Elements

Add new elements to an indexed array dynamically.

my_array+=(value5 value6)
echo "${my_array[@]}"  # Outputs: value1 value2 value3 value4 value5 value6

For associative arrays, simply assign a value to a new key.

my_assoc_array[new_key]=new_value

Array Length

Retrieve the length of an array to determine how many elements it contains.

echo "${#my_array[@]}"        # For indexed arrays
echo "${#my_assoc_array[@]}"  # For associative arrays

Deleting Elements

Remove specific elements from arrays using the unset command.

unset my_array[1]            # Removes the second element
unset my_assoc_array[key1]   # Removes the key-value pair

After deletion, the array remains valid but shrinks in size.

Practical Example: Merging Arrays

Combine two indexed arrays into one for processing.

array1=(1 2 3)
array2=(4 5 6)
merged_array=("${array1[@]}" "${array2[@]}")
echo "${merged_array[@]}"  # Outputs: 1 2 3 4 5 6

This approach maintains the order of elements from both arrays.

Debugging Tips

Use declare -p to display array contents during development.

declare -p my_array
declare -p my_assoc_array

Be mindful of quoting ("${array[@]}") to prevent word splitting when accessing elements.

By mastering arrays in Bash, you can handle complex data manipulations efficiently. With practice, these techniques will empower you to write concise and robust scripts tailored to a wide range of tasks.