bash shell script iterate through array values

Contributor Icon Contributed by qmchenry Date Icon August 30, 2004  
Tag Icon Tagged: Bourne shell scripting

Having an array of variables is of no use unless you can use those values somehow. This recipe shows a few methods for looping through the values of an array in the bash shell.


Given the array definition:

names=( Jennifer Tonya Anna Sadie )

The following expression evaluates into all values of the array:

${names[@]}

and can be used anywhere a variable or string can be used.

A simple for loop can iterate through this array one value at a time:

for name in ${names[@]}
do
echo $name
# other stuff on $name
done

This scrip will loop through the array values and print them out, one per line. Additional statements can be placed within the loop body to take further action, such as modifying each file in an array of filenames.

Sometimes it is useful to loop through an array and know the numeric index of the array you are using (for example, so that you can reference another array with the same index). The same loop in the example above can be achieved this way, too:

for (( i = 0 ; i < ${#names[@]} ; i++ ))
do
echo ${names[$i]}
# yadda yadda
done

In this example, the value ${#names[@]} evaluates into the number of elements in the array (4 in this case). The individual elements of the array are accessed, one at a time, using the index integer $i as ${names[$i]}

Previous recipe | Next recipe |
 
  • Fakeer
    all kinds of errors will popup if you write this (or any) script on windows. i was almost giving up when i realised i had written it on notepad and saved on the linux box over samba. use dostounix <scriptfile> to fix the format.
  • RobbyC
    The reason for this error is that the control character sequence used by DOS (Windows, \r\n) is different from the sequnce used by UNIX (*NIX, \n)
  • JamesDS
    ah, just what I was looking for - perfect, thanks!
  • mati
    if you really have to use windows, then cygwin is your salvation.
  • Olly
    Thank you very much for this snipped - just what I was looking for!
  • kool
    thnx a lot pal
    I owe u 5 marks of my final exam
    :)
blog comments powered by Disqus