Bash While and Until Loops - File Reading, Polling, Counters

Master bash while and until loops for reading files line by line, polling services, implementing counters, and building retry logic with practical examples.

Control Flow

Detailed Explanation

While and Until Loops in Bash

While loops repeat a block of commands as long as a condition is true. Until loops repeat until a condition becomes true. Both are essential for reading files, polling services, and implementing retry logic.

Basic While Loop

count=5
while [ $count -gt 0 ]; do
  echo "$count..."
  count=$((count - 1))
done
echo "Done!"

Reading Files Line by Line

The most common use of while loops is reading files:

while IFS= read -r line; do
  echo "Processing: $line"
done < input.txt

IFS= prevents leading/trailing whitespace trimming. -r prevents backslash interpretation.

Processing CSV Data

while IFS=',' read -r name email role; do
  echo "Creating account: $name ($email) - $role"
done < users.csv

Piping to While

# Process command output
ps aux | while read -r user pid cpu mem rest; do
  if (( $(echo "$mem > 10.0" | bc -l) )); then
    echo "High memory: PID $pid ($user) at $mem%"
  fi
done

Until Loop

# Wait for a service to be ready
until curl -sf http://localhost:3000/health > /dev/null 2>&1; do
  echo "Waiting for server..."
  sleep 2
done
echo "Server is up!"

Retry Logic

MAX_RETRIES=5
attempt=0

while [ $attempt -lt $MAX_RETRIES ]; do
  if deploy_application; then
    echo "Deployment successful"
    break
  fi
  attempt=$((attempt + 1))
  echo "Attempt $attempt failed, retrying in 10s..."
  sleep 10
done

if [ $attempt -eq $MAX_RETRIES ]; then
  echo "Deployment failed after $MAX_RETRIES attempts"
  exit 1
fi

Infinite Loop with Break

while true; do
  read -p "Enter command (quit to exit): " cmd
  case "$cmd" in
    quit) break ;;
    *) echo "You entered: $cmd" ;;
  esac
done

Monitoring Pattern

# Monitor disk usage
while true; do
  usage=$(df -h / | awk 'NR==2 {print $5}' | tr -d '%')
  if [ "$usage" -gt 90 ]; then
    echo "ALERT: Disk usage at $usage%"
  fi
  sleep 60
done

Use Case

While loops are essential for reading configuration files, processing log files line by line, implementing service health check polling, building retry mechanisms for unreliable operations (network requests, deployments), creating interactive command-line menus, and monitoring system resources at regular intervals.

Try It — Bash Cheat Sheet

Open full tool