Bash Looping Arrays
Looping an array runs the same code once for each item. A for loop can print each value and each index.
Loop over the values
The loop runs once for each color. Each run prints one value.
colors=(red green blue)
for item in "${colors[@]}"; do
echo "$item"
doneLoop over the indexes
The ! symbol changes @ into a list of indexes. The loop prints each index alone.
colors=(red green blue)
for i in "${!colors[@]}"; do
echo "$i"
donePrint index and value
The loop reads the value at each index. It prints the index and the value together.
colors=(red green blue)
for i in "${!colors[@]}"; do
echo "$i: ${colors[$i]}"
doneExample
fruits=(apple banana cherry)
for i in "${!fruits[@]}"; do
echo "$i: ${fruits[$i]}"
done
echo "Total is ${#fruits[@]}"Key points
- Use a for loop with "${colors[@]}" to visit every value.
- Quotes keep each array item as one whole value.
- Write ${!colors[@]} to get all the indexes of an array.
- Write ${colors[$i]} to read the value at index $i.
- An index and its value can build a label for each line.
In this example, the loop visits each index of the fruits array. Each run prints the index and the fruit at that index. The last line prints the item count from the earlier lesson.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does "${!colors[@]}" give a loop to visit?