How to loop over an array in Bash

By

Learn how to loop over an array in Bash using a for loop and the ${list[@]} syntax to iterate over every element and echo each one in turn.

~~~

To loop over an array in Bash, use a for loop with the "${list[@]}" syntax. It expands to every element of the array, one per iteration.

I had an array of 3 strings:

list=( "first" "second" "third" )

and I wanted to loop over them in a bash shell script.

Here’s how I did it:

for i in "${list[@]}"
do
  echo $i
done

This prints:

first
second
third

On each iteration, Bash assigns the next element to the variable i, and the loop body runs once per element.

Why the quotes matter

The quotes around "${list[@]}" are not optional. They tell Bash to keep each element intact, even when an element contains spaces.

Take this array:

files=( "notes.txt" "meeting recap.txt" )

With quotes, the loop runs twice, as expected. Without quotes, Bash splits meeting recap.txt on the space and the loop runs three times, with meeting and recap.txt as separate items.

That’s the most common mistake with Bash arrays. If your loop processes more items than your array contains, check the quotes first.

What about ${list[*]}?

There’s a similar syntax that uses * instead of @. When quoted, "${list[*]}" expands to a single string with all elements joined together:

for i in "${list[*]}"
do
  echo $i
done

This prints one line:

first second third

The loop only ran once. That’s rarely what you want when iterating, so stick with "${list[@]}" for loops.

How to loop with the index

Sometimes you need the position of each element, not just its value. Use "${!list[@]}" (note the !) to loop over the indexes:

for index in "${!list[@]}"
do
  echo "$index: ${list[$index]}"
done

This prints:

0: first
1: second
2: third

Bash arrays start at index 0.

Getting the array length

While we’re at it, you can get the number of elements with ${#list[@]}:

echo ${#list[@]}

This prints 3.

One last thing to be careful with: if you reference the array with just $list, without the brackets, Bash gives you only the first element. Writing echo $list prints first, not the whole array. Always use "${list[@]}" when you want all the elements.

Tagged: CLI · All topics
~~~

Related posts about cli: