Looping Arrays
Looping an array is like a teacher calling each student's name from the class list, one at a time, until everyone has had their turn.
In this page:
Syntax
for item in "${array_name[@]}"; do
commands using "$item"
done
Looping Arrays
for item in "${array[@]}" iterates directly over an array's values, which is the most idiomatic way to process every element.
Looping by index instead, with for i in "${!array[@]}", is useful when you need the position as well as the value. Quoting "${array[@]}" prevents elements containing spaces from being split apart.
Note:
- Prefer
for item in "${array[@]}"for simple value iteration - Use the index form only when you need the index too.
Example: Looping Arrays
#!/bin/bash
tasks=("Write code" "Run tests" "Deploy")
for task in "${tasks[@]}"; do
echo "- $task"
done
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
for i in ${arr[@]}without quotes, which splits items with spaces. - Using
${arr[*]}in a loop when you need each item separately. - Changing the array while looping over it.
🔒
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: