How to Iterate Array in Bash: Simple Loop Examples
In Bash, you can iterate over an array using a
for loop with the syntax for element in "${array[@]}"; do ... done. This loops through each item in the array, allowing you to process them one by one.Syntax
The basic syntax to iterate over an array in Bash is:
for element in "${array[@]}"; do- starts the loop, whereelementtakes each value.commands- commands to run for each element.done- ends the loop.
${array[@]} expands to all elements of the array.
bash
for element in "${array[@]}"; do echo "$element" done
Example
This example shows how to create an array and print each element using a for loop.
bash
# Define an array fruits=(apple banana cherry) # Loop through the array for fruit in "${fruits[@]}"; do echo "Fruit: $fruit" done
Output
Fruit: apple
Fruit: banana
Fruit: cherry
Common Pitfalls
Common mistakes when iterating arrays in Bash include:
- Using
${array[*]}without quotes, which concatenates all elements into one string. - Not quoting
"${array[@]}", causing word splitting and incorrect iteration. - Confusing array indices with values.
Always quote "${array[@]}" to preserve each element as a separate word.
bash
# Wrong way (no quotes, all elements combined): fruits=(apple banana cherry) for fruit in ${fruits[*]}; do echo "$fruit" done # Right way (quotes preserve elements): for fruit in "${fruits[@]}"; do echo "$fruit" done
Output
apple
banana
cherry
Fruit: apple
Fruit: banana
Fruit: cherry
Quick Reference
| Concept | Syntax | Description |
|---|---|---|
| Array definition | array=(val1 val2 val3) | Creates an array with elements. |
| Iterate array | for item in "${array[@]}"; do ... done | Loops over each element. |
| Access element | ${array[index]} | Gets element at position index. |
| Array length | ${#array[@]} | Number of elements in array. |
Key Takeaways
Use for loops with "${array[@]}" to iterate each element safely.
Always quote "${array[@]}" to avoid word splitting issues.
Define arrays with parentheses and space-separated values.
Access elements by index using ${array[index]}.
Check array length with ${#array[@]} when needed.