Web Analytics

While & Until Loops

Beginner ~20 min read

While and until loops provide condition-based iteration, unlike for loops that iterate over lists. While loops continue as long as a condition is true, and until loops continue until a condition becomes true. These loops are essential for reading files line by line, waiting for conditions, creating interactive scripts, and handling situations where you don't know in advance how many iterations you need!

While Loop Basics

A while loop executes its body as long as the condition remains true. The condition is checked before each iteration.

Output
Click Run to execute your code
# Basic syntax
while [ condition ]; do
    # code to execute while condition is true
done

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

# Output:
# Count: 1
# Count: 2
# Count: 3
# Count: 4
# Count: 5
Key Points:
- Condition is checked before each iteration
- Loop continues while condition is true
- Make sure condition eventually becomes false to avoid infinite loops
- Update loop variable inside the loop body

Until Loop

An until loop is the opposite of a while loop. It continues until the condition becomes true (i.e., while the condition is false).

Output
Click Run to execute your code
# Basic syntax
until [ condition ]; do
    # code to execute until condition becomes true
done

# Example: Countdown
num=5
until [ $num -eq 0 ]; do
    echo "Countdown: $num"
    num=$((num - 1))
done
echo "Blast off!"

# While vs Until comparison:
# while: continues WHILE condition is true
# until: continues UNTIL condition becomes true (while condition is false)
When to Use:
- Use while when you want to continue while something is true
- Use until when you want to continue until something becomes true
- while is more commonly used than until

Reading Files Line by Line

While loops are perfect for reading files line by line. This is one of the most common uses of while loops in Bash.

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

# Explanation:
# - IFS= preserves leading/trailing whitespace
# - read -r reads a line (r prevents backslash interpretation)
# - < file.txt redirects file content to stdin

# Processing each line
while IFS= read -r line; do
    if [[ -n "$line" ]]; then  # Skip empty lines
        echo "Processing: $line"
    fi
done < file.txt

# Reading from command output
command | while IFS= read -r line; do
    echo "Output: $line"
done
Important: When using while read in a pipeline, the loop runs in a subshell, so variables set inside won't persist. Use process substitution or file redirection instead:
while read line; do ... done < file.txt
command | while read line; do ... done ✗ (subshell)

Infinite Loops

Infinite loops continue forever until explicitly broken. They're useful for interactive programs, servers, and monitoring tasks.

# Infinite while loop
while true; do
    echo "This runs forever..."
    sleep 1
    # Use break to exit
done

# Infinite until loop (rarely used)
until false; do
    echo "This also runs forever..."
    sleep 1
done

# Controlled infinite loop
counter=0
while true; do
    counter=$((counter + 1))
    echo "Iteration: $counter"
    
    if [ $counter -ge 5 ]; then
        echo "Breaking at iteration $counter"
        break
    fi
done
Infinite Loop Tips:
- Always provide a way to exit (break, condition check, or signal handling)
- Use sleep in loops that run frequently to avoid high CPU usage
- Consider adding timeout mechanisms for long-running loops

While with Command Conditions

While loops can use command exit codes as conditions. The loop continues while the command succeeds (exit code 0).

# While command succeeds
while command; do
    # code
done

# Example: Wait for file to exist
while [ ! -f /tmp/flag.txt ]; do
    echo "Waiting for file..."
    sleep 1
done
echo "File found!"

# Example: Process until command fails
while ping -c 1 google.com &> /dev/null; do
    echo "Network is up"
    sleep 5
done
echo "Network is down"

Common Mistakes

1. Infinite loop without exit condition

# Wrong - never updates count
count=1
while [ $count -le 5 ]; do
    echo "$count"
    # Missing: count=$((count + 1))
done  # Infinite loop!

# Correct - update variable inside loop
count=1
while [ $count -le 5 ]; do
    echo "$count"
    count=$((count + 1))  # Update loop variable
done

2. Using for instead of while for file reading

# Wrong - splits on spaces, not lines
for line in $(cat file.txt); do
    echo "$line"
done

# Correct - use while read
while IFS= read -r line; do
    echo "$line"
done < file.txt

3. Variables in pipeline subshell

# Wrong - count won't persist (subshell)
count=0
cat file.txt | while read line; do
    count=$((count + 1))
done
echo "Lines: $count"  # Prints 0!

# Correct - use file redirection
count=0
while read line; do
    count=$((count + 1))
done < file.txt
echo "Lines: $count"  # Correct count

Exercise: Create a File Processor

Task: Create a script that uses while loops to process data!

Requirements:

  • Use a while loop to count from 1 to 10
  • Create an infinite loop that breaks after 5 iterations
  • Use while read to process lines (simulate with echo)
  • Compare while and until loops side by side
  • Use a while loop to wait for a condition
Show Solution
#!/bin/bash
# While loop exercises

# 1. Count 1-10
echo "Counting 1-10:"
count=1
while [ $count -le 10 ]; do
    echo "  $count"
    count=$((count + 1))
done

# 2. Infinite loop with break
echo -e "\nInfinite loop (breaks at 5):"
counter=0
while true; do
    counter=$((counter + 1))
    echo "  Iteration: $counter"
    if [ $counter -ge 5 ]; then
        break
    fi
done

# 3. While read (simulated)
echo -e "\nProcessing lines:"
echo -e "line1\nline2\nline3" | while IFS= read -r line; do
    echo "  Processing: $line"
done

# 4. While vs Until comparison
echo -e "\nWhile loop (count up):"
i=1
while [ $i -le 3 ]; do
    echo "  $i"
    i=$((i + 1))
done

echo -e "\nUntil loop (count up - same logic):"
i=1
until [ $i -gt 3 ]; do  # Note: condition is opposite
    echo "  $i"
    i=$((i + 1))
done

Summary

  • While: while [ condition ]; do ... done continues while true
  • Until: until [ condition ]; do ... done continues until true
  • File Reading: Use while IFS= read -r line; do ... done < file
  • Infinite: while true; do ... done with break or condition
  • Update Variable: Always update loop variable inside loop body
  • Pipeline: Avoid command | while (subshell); use redirection
  • Command Condition: Loop continues while command succeeds (exit 0)
  • When to Use: When iterations depend on conditions, not list items

What's Next?

Excellent! You've mastered while and until loops. Next, we'll learn about Loop Control statements - break, continue, exit, and return. These give you fine-grained control over loop execution and script flow!