Warning: Invalid argument supplied for foreach() in /home/techrecipes/public_html/wp-content/themes/techrecipes/header.php on line 77

Bash Shell Script Iterate Through Array Values

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


Take, for example, the array definition below:

names=( Jennifer Tonya Anna Sadie )

The following expression evaluates into all values of the array:

${names[@]}

It also 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 script 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]}

 

About Quinn McHenry

Quinn was one of the original co-founders of Tech-Recipes. He is currently crafting iOS applications as a senior developer at Small Planet Digital in Brooklyn, New York.
View more articles by Quinn McHenry

The Conversation

Follow the reactions below and share your own thoughts.

  • Anonymous

    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 to fix the format.

    • RobbyC

      The reason for this error is that the control character sequence used by DOS (Windows, rn) is different from the sequnce used by UNIX (*NIX, n)

    • TuxSax

      I had a similar problem until I realized that the file I was working on was created on Windows too.
      I fixed it with:
      sed -i ‘s/r$//’

      • TuxSax

        Right, I’ve forgot to mention that option too
        If you are working on Ubuntu, like me, then the package “tofrodos” contains the dos2unix utility.

    • Reginald Pierce

      I have found Notepad++ to be a great tool for Windows since it allows you to convert the line endings to Windows, Mac, or Linux while editing the file.  It also has good code highlighting.

  • 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
    :)

  • Anonymous

    Thanks a lot..

  • Thanish

    Thanks for the for function m8, you just saved me some hours.
    Now I can get back to my Script. You guys can also place the ‘do’ on the first line
    IMHO it looks better this way.

    for name in ${names[@]}; do

    • minoc

      as long as names are not separated by IFS (defaulting to white space).. for example

      names=( “foo bar” “ben smith” )
      for name in ${names[@]}; do echo “[${name}]“; done
      [foo]
      [bar]
      [ben]
      [smith]

      whereas this preserves the spacing in array elements:

      for ((i=0; i

      • minoc

        Oops., The easiest way to iterate is like you said initially., except you forgot the quotes:

        for name in “${names[@]}”; do

        works., and preserves the internal spaces in the elements…

      • Jack

        Iterate through a sparse array by using:

        ARR=([0]=”zero” [1]=”one” [10]=”ten”)
        for INDEX in ${!ARR[@]}
        do
        echo index $INDEX “=>” ${ARR[$INDEX]}
        done

  • annie

    great!…
    i really need this
    thanks

  • sriram

    it works perfectly

    Thanks a lot

  • http://www.thebusschedule.com sitami

    what must I do whene I only want to use the frist element of the array?

  • spike

    Awesome tips!

  • Kevin

    Hi, great tip! However, I think the loop needs a semicolon before the word “do”, i.e:

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

  • punit

    cant stote,
    x[08]=”Annthing”
    also
    x[09]=”Annthing”

    Only on this 2 key values it gives error
    -bash: 08: value too great for base (error token is “08″)
    -bash: 08: value too great for base (error token is “09″)

    Any solution ???

  • Nils

    When i use the ${array[@]} format to loop over the elements of the array, the sequence it shows is wrong though the elements are all present!
    Any idea why?

  • Calvin Morrison

    This is good, but you have a syntax error in the loop

    it should look like:
    for (( i=0; i < ${#names[@]} ; i++ )) do

    because bash won't deal with spaces correclty

  • Dark Star

    When you want all the elements in an array as arguments do NOT use:

    ${names[@]}

    unless you want spaces to break your code, use:

    “${names[@]}”

    With the double quotes. It is a special case with @ array expansion inside double quotes that it generates N arguments instead of just one.