The For Loop

When to Use For Loops

  • When you have a list of items to process (files, directories, strings, etc.)
  • When you need to repeat an action a specific number of times
  • When processing array elements or command output
  • When you know exactly how many iterations you need
  • When iterating over a sequence of numbers

Common For Loop Options

Syntax What It Does When to Use It
for var in item1 item2 ... Loops through a list of specified items When you have a predefined list
for var in $(command) Loops through command output When processing the result of a command
for var in {1..10} Loops through a range of numbers When iterating a specific number of times
for var in *.txt Loops through files matching a pattern When processing files of a specific type
for ((i=0; i<5; i++)) C-style for loop with initialization, condition, and increment When you need more control over the loop counter

Practical Examples

# Basic for loop with list
for name in Alice Bob Charlie Dave; do
    echo "Hello, $name!"
done

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

# Process all text files in current directory
for file in *.txt; do
    echo "Processing $file..."
    wc -l "$file"  # Count lines in each file
done

# Use command output in a loop
for user in $(cat users.txt); do
    echo "Creating home directory for $user"
    # mkdir /home/$user  # Commented out for safety
done

# C-style for loop
for ((i=0; i<5; i++)); do
    echo "Iteration $i"
done

The While Loop

When to Use While Loops

  • When you need to repeat until a condition changes
  • When processing input line by line
  • When you need to wait for something to happen
  • When the number of iterations isn't known in advance
  • When implementing counters or timers

Common While Loop Options

Syntax What It Does When to Use It
while [[ condition ]] Repeats while condition is true When looping based on a Boolean condition
while read line Processes input line by line When processing file contents or command output
while : # (colon is always true) Creates an infinite loop When implementing services or monitors that run until manually stopped

Practical Examples

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

# Read file line by line
while read line; do
    echo "Line: $line"
done < input.txt

# Wait for a file to exist
while [[ ! -f /tmp/signal_file ]]; do
    echo "Waiting for signal file..."
    sleep 5
done
echo "Signal file detected!"

# Menu system with while loop
choice=""
while [[ "$choice" != "q" ]]; do
    echo "Menu:"
    echo "1. Show date"
    echo "2. List files"
    echo "q. Quit"
    read -p "Enter choice: " choice
    
    case $choice in
        1) date ;;
        2) ls -la ;;
        q) echo "Exiting..." ;;
        *) echo "Invalid choice" ;;
    esac
done

The Until Loop

When to Use Until Loops

  • When you want to repeat until a condition becomes true
  • When waiting for something to become available
  • When the exit condition is more naturally expressed than the continuation condition
  • When implementing retries until success
  • When a process needs to run until completion

Common Until Loop Options

Syntax What It Does When to Use It
until [[ condition ]] Repeats until condition becomes true When the exit condition is clearer than the continuation condition

Practical Examples

# Basic until loop with counter
count=1
until [[ $count -gt 5 ]]; do
    echo "Count: $count"
    count=$((count + 1))
done

# Retry a command until it succeeds
until ping -c 1 example.com &> /dev/null; do
    echo "Waiting for network connection..."
    sleep 5
done
echo "Network is up!"

# Wait until a specific time
current_time=$(date +%H%M)
until [[ $current_time -ge 0900 ]]; do
    echo "Waiting for 9:00 AM. Current time: $current_time"
    sleep 60
    current_time=$(date +%H%M)
done
echo "It's 9:00 AM or later, starting process..."

Advanced Loop Techniques

When to Use Advanced Techniques

  • When you need to exit loops early
  • When you want to skip certain iterations
  • When implementing complex nested loops
  • When combining loops with decision making
  • When processing complex data structures

Advanced Loop Techniques

Technique What It Does When to Use It
Nested loops Puts one loop inside another When processing multi-dimensional data or combinations
break Exits the current loop When a termination condition is met mid-loop
continue Skips to the next iteration When certain items should be skipped
Loop with if/else Adds conditional logic inside loops When different actions are needed for different items

Practical Examples

# Nested loops
for i in {1..3}; do
    for j in {a..c}; do
        echo "Combination: $i$j"
    done
done

# Using break to exit a loop early
for num in {1..10}; do
    if [[ $num -eq 5 ]]; then
        echo "Reached 5, stopping loop"
        break
    fi
    echo "Number: $num"
done

# Using continue to skip iterations
for num in {1..5}; do
    if [[ $num -eq 3 ]]; then
        echo "Skipping 3"
        continue
    fi
    echo "Processing: $num"
done

# Loop with if/else logic
for file in *.txt; do
    if [[ -s "$file" ]]; then
        echo "$file has content, processing..."
    else
        echo "$file is empty, skipping"
    fi
done

# Processing user input in a loop with exit condition
while true; do
    read -p "Enter a command (or 'quit' to exit): " cmd
    
    if [[ "$cmd" == "quit" ]]; then
        echo "Exiting..."
        break
    fi
    
    # Process the command
    echo "Executing: $cmd"
    eval "$cmd"
done