Looping in Bash

Contents

Note: This guide ensures compatibility with Bash 3, which is the default on macOS and some older systems. All examples should work across Bash 3 and newer versions.

For Loop in Bash

For loops are the most commonly used loops in Bash for iterating over a series of values.

for item in list
do
    echo "$item"
done

For Loop Variations

C-style For Loop

for ((i=0; i<10; i++))
do
    echo "$i"
done

For Loop with Range

for i in $(seq 1 5)
do
    echo "$i"
done
Note: In Bash 4+, you can use {1..5} for ranges, but seq is more compatible across versions (including v3).

One-line For Loop

for i in $(seq 1 5); do echo "$i"; done

Bash While Loop

While loops continue executing as long as a condition is true.

count=1
while [ $count -le 5 ]
do
    echo "$count"
    count=$((count + 1))
done

Bash For Loop Array

Looping through arrays is a common task in Bash scripting.

fruits=("apple" "banana" "cherry")
for fruit in "${fruits[@]}"
do
    echo "$fruit"
done

Bash Loop Through Files in Directory

for file in *
do
    echo "Processing $file"
done
Tip: When dealing with filenames that might contain spaces, always quote your variables: "$file"

Bash Infinite Loop

while true
do
    echo "This will run forever"
    sleep 1
done

Bash Until Loop

Until loops continue executing until a condition becomes true.

count=1
until [ $count -gt 5 ]
do
    echo "$count"
    count=$((count + 1))
done

Bash Loop Control

Break Statement

for i in $(seq 1 10)
do
    if [ $i -eq 5 ]
    then
        break
    fi
    echo "$i"
done

Continue Statement

for i in $(seq 1 5)
do
    if [ $i -eq 3 ]
    then
        continue
    fi
    echo "$i"
done