Introduction

Hello! In this article, we’ll learn about while loops.

while is a construct that repeats processing while a condition is true. Similar to for, but used when the number of iterations isn’t fixed, or when you want to repeat based on conditions.

What is a while Loop?

while is a control structure that keeps repeating processing as long as a specified condition is true.

“Wait until file is found”, “keep going until user enters ‘quit’” - useful when the end isn’t clearly defined.

Basic Syntax

1
2
3
while [ condition ]; do
    # Processing to repeat while condition is true
done

Usage Examples

Example 1: Counter Loop

1
2
3
4
5
6
count=1

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

Output:

1
2
3
4
5
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Example 2: Infinite Loop

1
2
3
4
while true; do
    echo "Infinite loop... (Ctrl+C to exit)"
    sleep 1
done

Since true is always true, it repeats forever. Stop with Ctrl+C.

Example 3: Read File Line by Line

1
2
3
while read line; do
    echo "Line: $line"
done < file.txt

Process file contents line by line. I use this a lot.

Example 4: User Input Loop

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
while true; do
    read -p "Enter command (quit to exit): " cmd

    if [ "$cmd" = "quit" ]; then
        echo "Exiting"
        break
    fi

    echo "Input: $cmd"
done

Example:

1
2
3
4
5
6
Enter command (quit to exit): hello
Input: hello
Enter command (quit to exit): test
Input: test
Enter command (quit to exit): quit
Exiting

Example 5: Wait for File Creation

1
2
3
4
5
6
7
8
file="signal.txt"

while [ ! -f "$file" ]; do
    echo "Waiting for file: $file"
    sleep 2
done

echo "File found!"

Keeps looping until file is created.

Example 6: Count Down

1
2
3
4
5
6
7
8
9
count=5

while [ $count -gt 0 ]; do
    echo "Remaining: $count"
    sleep 1
    count=$((count - 1))
done

echo "Done!"

Output:

1
2
3
4
5
6
Remaining: 5
Remaining: 4
Remaining: 3
Remaining: 2
Remaining: 1
Done!

Can make countdowns like this too.

Tips & Notes

  • Beware infinite loops: Always true condition means it never stops

    1
    2
    3
    4
    
    # This never stops
    while true; do
        echo "Never stops"
    done
    

    Make sure you can stop with Ctrl+C or have a break to exit.

  • break and continue: Control the loop

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    
    while true; do
        read -p "Input: " input
        if [ "$input" = "exit" ]; then
            break  # Exit loop
        fi
        if [ -z "$input" ]; then
            continue  # Skip to next iteration if empty
        fi
        echo "Processing: $input"
    done
    
  • File reading caution: Watch variable scope when using pipes

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    
    # Variables don't persist this way
    cat file.txt | while read line; do
        count=$((count + 1))
    done
    echo $count  # Empty
    
    # This is correct
    while read line; do
        count=$((count + 1))
    done < file.txt
    echo $count  # Has value
    
  • Add sleep for intervals: Avoid continuous execution

    1
    2
    3
    4
    
    while true; do
        # Some processing
        sleep 1  # Wait 1 second
    done
    

Practical Usage

Monitoring Script

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#!/bin/bash

log_file="/var/log/app.log"

while true; do
    if grep -q "ERROR" "$log_file"; then
        echo "Error detected!"
        # Notification processing etc.
    fi
    sleep 10  # Check every 10 seconds
done

Monitor log files continuously.

Wait for Process

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/bin/bash

process="myapp"

while pgrep "$process" > /dev/null; do
    echo "Process running: $process"
    sleep 5
done

echo "Process finished"

Wait for specific process to end.

Monitor Disk Usage

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#!/bin/bash

threshold=80

while true; do
    usage=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')

    if [ $usage -gt $threshold ]; then
        echo "Warning: Disk usage at ${usage}%"
    fi

    sleep 60  # Check every minute
done

Interactive Menu

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/bin/bash

while true; do
    echo "=== Menu ==="
    echo "1. File list"
    echo "2. Disk usage"
    echo "3. Exit"
    read -p "Select: " choice

    case $choice in
        1)
            ls -la
            ;;
        2)
            df -h
            ;;
        3)
            echo "Exiting"
            break
            ;;
        *)
            echo "Invalid selection"
            ;;
    esac

    echo
done

Can make simple interactive menus.

Retry Processing

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash

max_retry=3
count=0

while [ $count -lt $max_retry ]; do
    echo "Attempting connection... ($((count + 1))/$max_retry)"

    if ping -c 1 google.com > /dev/null 2>&1; then
        echo "Connection successful!"
        break
    fi

    count=$((count + 1))
    sleep 2
done

if [ $count -eq $max_retry ]; then
    echo "Connection failed"
    exit 1
fi

Retry on failure.

File Processing (Line by Line)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#!/bin/bash

total=0

while read line; do
    # Sum numeric-only lines
    if [[ "$line" =~ ^[0-9]+$ ]]; then
        total=$((total + line))
    fi
done < numbers.txt

echo "Total: $total"

Summary

In this article, we learned about while loops.

Key Points:

  • while repeats processing while condition is true
  • Useful when number of iterations isn’t fixed
  • Can exit loops with break
  • Beware infinite loops (make sure Ctrl+C works)

Use for when iterations are fixed, while when you want to repeat based on conditions. Monitoring scripts, wait processing, lots of uses - good to remember.

Keep learning Linux commands!