Bash Arrays

Updated on

6 min read

Bash Arrays

Arrays are one of the most used and fundamental data structures. You can think of an array as a variable storing multiple variables within it. Arrays offer a convenient way to represent and manipulate a group of related data elements as a single entity.

In this article, we’ll cover the Bash arrays and explain how to use them in your Bash scripts.

Bash Arrays

Bash supports one-dimensional numerically indexed and associative array types. Numerical arrays are referenced using integers and associative using strings.

Numerically indexed arrays can be accessed from the end using negative indices; the index of -1 references the last element. The indices do not have to be contiguous.

Unlike most programming languages, Bash array elements don’t have to be of the same data type. This means you can create an array containing both strings and numbers.

Bash does not support multidimensional arrays, and you can’t have array elements that are also arrays.

There is no limit on the maximum number of elements that can be stored in an array.

Creating Bash Arrays

In Bash, arrays can be initialized using several different methods.

Creating numerically indexed arrays

Bash variables are untyped. Any variable can be used as an indexed array without declaring it.

To explicitly declare an array, use the declare builtin:

declare -a array_name

One way to create an indexed array is by using the following form:

array_name[index_1]=value_1
array_name[index_2]=value_2
array_name[index_n]=value_n

Where index_* is a positive integer.

Another way to create a numeric array is to specify the list of the elements within parentheses, separated by empty space:

array_name=( element_1 element_2 element_N )

When the array is created using the form above, indexing starts at zero, i.e., the first element has an index of 0.

Creating associative arrays

Associative arrays are a type of array where each element is identified by a unique key instead of an index.

Unlike numerically indexed, the associative arrays must be declared before they can be used.

To declare an associative array, use the declare builtin with the -A (uppercase) option:

declare -A array_name

Associative arrays are created using the following form:

declare -A array_name

array_name[index_foo]=value_foo
array_name[index_bar]=value_bar
array_name[index_xyz]=value_xyz

Where index_* can be any string.

You can also create an associative array using the form below:

declare -A array_name

array_name=( 
  [index_foo]=value_foo 
  [index_bar]=value_bar 
  [index_xyz]=value_xyz 
)

Array Operations

If you’re new to Bash programming, arrays in Bash can be confusing at first. However, after reading this article, you will understand them better.

Reference Elements

To reference a single element, you need to know the element index.

Any element can be referenced using the following syntax:

${array_name[index]}
The syntax for accessing an array element is similar to the syntax of most of the programming languages. The curly braces ${} are required to avoid the shell’s filename expansion operators.

Let’s print the element with an index of 1:

## declare the array
declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

## print element
echo ${my_array[1]}
Helium

If you use @ or * as an index, the word expands to all members of the array.

To print all elements, you would use:

## declare the array
declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

## print all elements
echo "${my_array[@]}"
Hydrogen Helium Lithium Beryllium

The only difference between @ and * is when the form ${my_array[x]} is surrounded by double quotes. In this case, * expands to a single word where array elements are separated with space. @ expands each array element to a separate word. This is especially important when using the form to illiterate through array elements.

To print the keys of the array, add the ! operator before the array name:

${!array_name[index]}

Here is an example:

## declare the array
declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

## print all elements
echo "${!my_array[@]}"
0 1 2 3

Array Length

If you want to determine the number of elements in an array, you can use the following syntax to get the array length:

${#array_name[@]}
The syntax is the same as when referencing all elements with the addition of the # character before the array name.
## declare the array
declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

## array Length
echo ${#my_array[@]}
4

Loop through the array

When you have an array of items, you often need to perform an operation on each item. One way to achieve this is by iterating over the array using a loop. The for loop allows you to access each item in the array individually and perform the desired operation on it.

declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

## Array Loop
for i in "${my_array[@]}"
do 
  echo "$i"
done

The code above will iterate over the array and print each element in a new line:

Hydrogen
Helium
Lithium
Beryllium

Here is an example of how to print all keys and values:

declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

## Array Loop
for i in "${!my_array[@]}"
do
  echo "$i" "${my_array[$i]}"
done
0 Hydrogen
1 Helium
2 Lithium
3 Beryllium

Another way to loop through an array is to get the length of the array and use the C-style loop:

declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

# Length of the array
length=${#my_array[@]}

# Array Loop
for (( i=0; i < ${length}; i++ ))
do
  echo $i ${my_array[$i]}
done
0 Hydrogen
1 Helium
2 Lithium
3 Beryllium

Adding a new element

To add a new element to a bash array and specify its index, use the following form:

my_array[index_n]="New Element"

Here is an example:

declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

## add new element
my_array[9]="Aluminum"

## print all elements
echo "${my_array[@]}"
Hydrogen Helium Lithium Beryllium Aluminum

Another way of adding a new element to an array without specifying the index is by using the += operator. You can add one or multiple elements:

declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

## add new elements
my_array+=( Cobalt Nickel )

## print all elements
echo "${my_array[@]}"
Hydrogen Helium Lithium Beryllium Cobalt Nickel

Delete an element

To delete a single element, you’ll need to know the element index. An element can be removed using the unset command:

unset my_array[index]

Let’s see an example:

declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

## remove element
unset my_array[2]

## print all elements
echo "${my_array[@]}"
Hydrogen Helium Beryllium

Conclusion

We’ve explain how to create numerically indexed and associative arrays. We have also show how to iterate through the arrays, calculate the array length, and add and remove elements.

If you have any questions or feedback, feel free to leave a comment.