Open Source

Using arrays in bash

Learn two ways two declare an array in bash in this Linux tip.

Assigning variables in bash is easily done and extremely useful, but like other programming languages, bash can also use arrays. This is particularly handy when you want to read the contents of a file into an array or simply keep your scripts more organized and logical.

There are two ways of declaring an array:

declare -a FOO

This creates an empty array called FOO. You can also declare an array by assigning values to it:

FOO[2] = 'bar'

This assigns the third element of the array to the value 'bar'. In this instance, FOO[0] and FOO[1] are also created, but their values are empty.

To populate an array, use:

FOO=( bar string 'some text' )

This assigns the first element (FOO[0]) to 'bar', the second (FOO[1]) to 'string' and the final element (FOO[3]) to 'some text'. Notice that the array elements are separated by a blank space, so if a value contains white spaces it must be quoted.

To use an array, it is referred to as $FOO[2] but it also needs to be surrounded in curly braces, otherwise bash will not expand it correctly:

$ echo {$FOO[2]}
some text

To loop through an array, you can use a piece of shell code like the following:

FOO=( bar string 'some text')
for ((i=0;i<$foonum;i++)); do
   echo ${FOO[${i}]}

Here we loop through each item of the array and print out its value. Each array element is accessed by number, so we use the special variable ${#FOO} which gives the number of elements in the array (in the above case, it would return the number 3). That value is then used in the for loop to determine how many times to loop. By accessing the array in this manner, you can easily generate arrays from external data or command-line arguments, and process each element one at a time.

Delivered each Tuesday, TechRepublic's free Linux NetNote provides tips, articles, and other resources to help you hone your Linux skills. Automatically sign up today!

About Vincent Danen

Vincent Danen works on the Red Hat Security Response Team and lives in Canada. He has been writing about and developing on Linux for over 10 years and is a veteran Mac user.

Editor's Picks

Free Newsletters, In your Inbox