Using arrays in bash

Tags: Linux, Vincent Danen, Foo, Linux Tips Newsletter

  • Save
  • Print
  • Digg This
  • 1

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!

  • Save
  • Print
  • Digg This
  • 1

Print/View all Posts Comments on this article

More bash scripting tipsDanLM  | 08/09/05
Have you checked out the Tony K  | 08/09/05
Mistakes?kiri@...  | 08/10/05
Semantic error8ored  | 08/22/05

What do you think?

TechRepublic Featured Jobs

Job Title/Location Posted
Help Desk SupportLake Forest, CA 01/08/2008
Help Desk Network SupportGoshen, NY 01/02/2008
Help DeskGardner, KS 01/11/2008
Help DeskHouston, TX 11/07/2007
  • Powered by: Simply Hired
  • .

White Papers


advertisement
Click Here