Looping
Values
fruits=("apple" "banana" "cherry")
for fruit in "${fruits[@]}"; do
echo "$fruit"
done
Output
apple
banana
cherry
Loops over array values safely. Quoting "${fruits[@]}" keeps one element per iteration, even when values contain spaces; see arrays.
Indices
for i in "${!fruits[@]}"; do
echo "$i: ${fruits[$i]}"
done
Output
0: apple
1: banana
2: cherry
Loops over array indices. ! expands to the indices, which is useful when the position matters; see arrays.
C-style loop
for ((i = 0; i < ${#fruits[@]}; i++)); do
echo "${fruits[i]}"
done
Loops with a numeric index. ${#array[@]} is the array length; this form is handy when you need the index. See arrays.
Related links
- Bash arrays (gnu.org)
0 Comments for this cheatsheet. Write yours!