How to Use Arrays in Bash Made Simple

Bash may not be a full programming language, but it is a good scripting language and every scripting language needs support for arrays. This post is about the simple way to declare arrays in Bash shell scripts and make use of them.

Declaring Arrays

  • You can declare arrays by index (does not need to be zero):
my_array[1]="An Element"
  • You can do it out of order:
my_array[3]="An Element"
my_array[1]="Another Element"
my_array[2]="And Another Element"
  •  You can skip indices:
my_array[19]="An Element"
my_array[7]="Another Element"
my_array[11]="And Another Element"
  • Best of all, you can do it all at once on one line:
my_array= ("One" "Two" "Three" "Four" "Five" "Six")
  • When you do the above declaration, the Bash shell will start the indices at 0 (zero-based)

Accessing an Array in Bash

  • You simply access the array by the index:
my_array=("The cake is a lie")
echo $my_array[1]

$ The cake is a lie

Accessing Array Properties in Bash

  •  There are a variety of special commands to access array properties:
my_array=( "One" "Two" "Three" "Four" "Five" )

# Print the entire contents of an array:
echo ${my_array[@]}

$ One Two Three Four Five

# Print the number of elements in an array:
echo ${#my_array[@]}

$ 5

# Print the length of the element at index 0 (in this case, "One"):
echo ${#my_array[0]}

$ 3

# Print out the index numbers
echo ${!my_array[@]}

$ 0 1 2 3 4

echo ${!another_array[@]}

$ 5 12

Iterating Through a Bash Array

  • To iterate through a bash array, we treat it as a collection and step through each member:

my_array=( "One" "Two" "Three" "Four" "Five" )

for member in ${my_array[@]}
   echo ${member}

$ One
$ Two
$ Three
$ Four
$ Five

That’s it.


Karim Sultan
My vision is for digital innovation across the divide, by securing and simplifying the Internet and extending its reach to every citizen on Earth and beyond.

Leave a Reply

Your email address will not be published. Required fields are marked *