Objective

Write for, while, and until loops in bash to automate repetitive tasks, iterate over files and lists, and build robust automation scripts.

Tools & Technologies

  • for
  • while
  • until
  • break
  • continue
  • seq

Key Commands

for f in *.log; do
while read line; do
until ping -c1 host; do
for i in $(seq 1 10); do

Architecture Overview

flowchart TD INIT[Initialize] --> FOR_CHECK{More items\nin list?} FOR_CHECK -->|yes| BODY[Loop body\nexecutes] BODY --> BREAK{break?} BREAK -->|yes| EXIT[Exit loop] BREAK -->|no| CONT{continue?} CONT -->|yes| FOR_CHECK CONT -->|no| FOR_CHECK FOR_CHECK -->|no more| EXIT EXIT --> AFTER[Code after loop] style BREAK fill:#1a1a2e,stroke:#ff4444,color:#ff4444 style EXIT fill:#1a1a2e,stroke:#00ff88,color:#e0e0e0

Step-by-Step Process

01
for Loop

Iterate over a list of values, files, or command output.

# Over a list
for FRUIT in apple banana cherry; do
  echo "I like $FRUIT"
done

# Over files
for FILE in /var/log/*.log; do
  echo "Processing: $FILE"
done

# With seq (C-style range)
for i in $(seq 1 5); do
  echo "Step $i"
done

# C-style for
for ((i=0; i<5; i++)); do
  echo $i
done
02
while Loop

Loop while a condition is true. Essential for reading file contents line by line.

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

# Read file line by line
while IFS= read -r LINE; do
  echo "Line: $LINE"
done < /etc/hosts

# Infinite loop with break
while true; do
  ping -c1 -W1 8.8.8.8 > /dev/null && break
  echo 'Waiting for network...'
  sleep 2
done
03
until Loop

Until is the inverse of while — loops until the condition becomes true.

RETRIES=0
until ping -c1 server.local > /dev/null 2>&1; do
  echo 'Server not ready, waiting...'
  sleep 5
  ((RETRIES++))
  if [ $RETRIES -ge 10 ]; then
    echo 'Timeout!'
    exit 1
  fi
done
echo 'Server is up!'
04
Practical Loop Examples

Real automation tasks using loops.

#!/bin/bash
# Backup multiple directories
for DIR in /etc /home /var/www; do
  ARCHIVE="backup_$(basename $DIR)_$(date +%Y%m%d).tar.gz"
  tar -czf "/backup/$ARCHIVE" "$DIR"
  echo "Backed up $DIR → $ARCHIVE"
done

# Process all CSV files
for CSV in data/*.csv; do
  python3 process.py "$CSV"
done

Challenges & Solutions

  • Forgetting done after a loop causes syntax error
  • Modifying a list while iterating over it with for produces unpredictable results

Key Takeaways

  • Use while IFS= read -r line to safely process files with spaces in lines
  • break and continue work the same as in C — break exits, continue skips to next iteration