Intermediate · 10 min · practise every command in the built-in terminal

Loops in Bash

for loop — iterate over items

# Loop over a list
for name in Alice Bob Charlie; do
    echo "Hello, $name!"
done

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

# Loop over array
FRUITS=(apple banana cherry)
for fruit in "${FRUITS[@]}"; do
    echo "$fruit"
done

# C-style loop
for ((i=1; i<=5; i++)); do
    echo "Count: $i"
done

# Loop over range
for i in {1..10}; do
    echo "$i"
done

for i in {0..20..5}; do    # Step of 5
    echo "$i"
done

while loop

COUNT=1
while [ $COUNT -le 5 ]; do
    echo "Iteration: $COUNT"
    ((COUNT++))
done

# Read lines from file
while IFS= read -r line; do
    echo "Line: $line"
done < file.txt

# Infinite loop
while true; do
    echo "Running..."
    sleep 1
    # break to exit
done

until loop

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

Loop control

break       # Exit the loop
continue    # Skip to next iteration

Practice tasks

  1. Write a for loop that prints numbers 1 to 5
  2. Write a for loop that lists all .txt files in the current directory
  3. Write a for loop that greets a literal list of names
  4. Write a for loop that prints each item of a fruit list

Commands in this lesson

Shell Scripting