Using arrays in bash

August 8, 2005


Takeaway:
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:

<code>
declare -a FOO
</code>

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

<code>
FOO[2] = 'bar'
</codE>

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:

<code>
FOO=( bar string 'some text' )
</code>

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:

<code>
$ echo {$FOO[2]}
some text
</code>

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

<code>

#!/bin/sh
FOO=( bar string 'some text')
foonum=${#FOO}

for ((i=0;i<$foonum;i++)); do
 echo ${FOO[${i}]}
done
</code>

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!

White Papers

Additional Resources

Tech Toolshed
http://www.techtoolshed.com

Learning CD-Roms
http://fasttrack.techrepublic.com

Quick Reference Charts
http://quickref.techrepublic.com

TechRepublic's Catalog
http://www.techrepublic.com/catalog

Copyright ©1995- 2003 CNET Networks, Inc. All Rights Reserved.
Visit us at www.TechRepublic.com