Intermediate โฑ 20 min Lesson 7 of 13

๐Ÿ”„ Loops

Iterate with for, while, and until loops. Control flow with break and continue.

Repeating Actions with Loops

Loops let you execute a block of commands repeatedly. They're essential for automation โ€” processing lists of files, retrying operations, counting, and more.

The for Loop

The for loop iterates over a list of items.

bash
# Loop over a list of words
for fruit in apple banana cherry; do
    echo "I like $fruit"
done

# Loop over files
for file in *.txt; do
    echo "Processing: $file"
done

# Loop over a range of numbers
for i in {1..5}; do
    echo "Number: $i"
done

# Range with step
for i in {0..20..5}; do
    echo "Count: $i"   # 0, 5, 10, 15, 20
done

# C-style for loop
for ((i = 0; i < 5; i++)); do
    echo "Index: $i"
done
๐Ÿ’ก Tip: Brace expansion {1..100} is expanded before the loop runs, so it's fast. For very large ranges, consider a while loop with arithmetic instead.

The while Loop

The while loop runs as long as a condition is true.

bash
# Count to 5
count=1
while [[ $count -le 5 ]]; do
    echo "Count: $count"
    ((count++))
done

# Infinite loop (be careful!)
while true; do
    echo "Press Ctrl+C to stop"
    sleep 1
done

The until Loop

until is the opposite of while โ€” it runs until the condition becomes true.

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

break & continue

break exits the loop entirely. continue skips the rest of the current iteration and moves to the next one.

bash
# break โ€” stop at 3
for i in {1..10}; do
    if [[ $i -eq 4 ]]; then
        break
    fi
    echo "$i"
done
# Output: 1 2 3

# continue โ€” skip even numbers
for i in {1..6}; do
    if (( i % 2 == 0 )); then
        continue
    fi
    echo "$i"
done
# Output: 1 3 5

Reading Files Line by Line

A common pattern is to read a file one line at a time using a while loop:

bash
# Read a file line by line
while IFS= read -r line; do
    echo "Line: $line"
done < myfile.txt

# Process CSV data
while IFS=, read -r name age city; do
    echo "$name is $age years old and lives in $city"
done < people.csv
โš ๏ธ Warning: Always use IFS= read -r to preserve whitespace and backslashes. Without these, lines may be mangled.

Try It Yourself

Terminal

Summary

You've mastered for loops (list, range, C-style), while and until loops, break and continue, and reading files line by line. Loops are the engine behind most automation scripts.

๐Ÿงช Test Your Knowledge

Answer the questions below to check your understanding of this lesson.