Bash Arrays With Examples

An array is a collection of elements. In Bash, an array can contain a mix of elements of different types, e.g. Strings and Numbers.

In this tutorial, we discuss how to create and use arrays in Bash. We will also cover array operations such as looping, printing, getting the size and modifying the contents.

How to Create Arrays in Bash

There are two ways we can create Bash arrays:

Using the declare keyword

declare -a my_bash_array

this will create an indexed array with the name “my_bash_array”.

Initializing an Array

We can also create and initialize arrays on the fly using the assignment operator = and the elements inside curly braces ():

my_bash_array=("apple" "orange" "banana")

Or, we could also specify the index explicitly

my_bash_array[0]="apple"
my_bash_array[1]="orange"
my_bash_array[2]="banana"

Bash Array Length

To get the length or size of an array, we use ${#array_name[@]}.

For example:

my_bash_array=(foo bar baz)
echo "the array contains ${#my_bash_array[@]} elements"

#Output
the array contains 3 elements

Bash Array Loop

To iterate through all elements in a Bash array, we can use the for loop:

#!/bin/bash

my_array=(foo bar baz)

# for loop that iterates over each element
for i in "${my_array[@]}"
do
    echo $i
done

Output:

foo
bar
baz

Printing all elements

To print all elements of an array without a loop, we can use the following syntax:

echo ${my_array[@]}

Adding Elements to Array

To add elements to an array we use the += operator. This will append an element to the end of the array.

For example:

my_array=(foo bar)
my_array+=(baz)

echo "${my_array[@]}"
foo bar baz

Or we can use the index to add an element:

my_array=(foo bar)
my_array[2]=baz

echo "${my_array[@]}"
foo bar baz

Delete Elements from Array

To delete an element from a Bash array, we use the unset command.

For example:

my_array=(foo bar baz)
unset my_array[1]
echo ${my_array[@]}
foo baz

Conclusion

In this tutorial we covered Bash arrays; how to create and initialize arrays in Bash and how to get the length, loop over elements, print elements and modify the contents of an array.