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

Looping Arrays

In this page:

  1. Looping Arrays

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

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.