← Back to Bash Course | Chapter 6: Arrays | Lesson 8 of 10

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:

  1. Looping Arrays
Syntax
bash
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

bash
#!/bin/bash
tasks=("Write code" "Run tests" "Deploy")

for task in "${tasks[@]}"; do
    echo "- $task"
done
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
  1. Using for i in ${arr[@]} without quotes, which splits items with spaces.
  2. Using ${arr[*]} in a loop when you need each item separately.
  3. Changing the array while looping over it.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.