Iterating through an array in Bash

I don’t like programming in bash but it does make some things very simple. Unfortunately, it is not obvious how to do some simple things like iterating through an array ;-)

Assuming that we have an array ITEMS=( a b c d ), we can use a ${ITEMS[@]} construct to iterate through all the elements in a for loop:

ITEMS=( a b c d )
for ITEM in ${ITEMS[@]}; do
    echo $ITEM
done

BTW: I found this pattern here.

Leave a Reply