A while loop in Bash is another control structure that repeatedly executes a block of commands as long as a specified condition is true. It’s particularly useful when you don’t know in advance how many times you need to loop, as the loop will continue until the condition is no longer met.

Basic Syntax

The basic syntax of a while loop in Bash is:

1
2
3
4
while [ CONDITION ]
do
# Commands to be executed
done

  • CONDITION is a test or expression that is checked before each iteration of the loop. If the condition evaluates to true, the loop body (the commands between do and done) is executed. If the condition evaluates to false, the loop exits.

    Example 1: Counting with a While Loop

    Here’s a simple example that counts from 1 to 5 using a while loop:

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

    counter=1

    while [ $counter -le 5 ]
    do
    echo "Counter: $counter"
    ((counter++))
    done

    Output:

    1
    2
    3
    4
    5
    Counter: 1
    Counter: 2
    Counter: 3
    Counter: 4
    Counter: 5

    Example 2: Waiting for a Condition

    You can use a while loop to wait for a specific condition to be met, such as waiting for a file to be created:

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

    while [ ! -f /path/to/file ]
    do
    echo "Waiting for file to be created..."
    sleep 1
    done

    echo "File has been created!"

    In this example, the loop will continue to check if the file exists every second (sleep 1) and only exit once the file is found.

    Example 3: Reading a File Line by Line

    A common use of while loops is reading a file line by line:

    1
    2
    3
    4
    5
    6
    #!/bin/bash

    while IFS= read -r line
    do
    echo "Line: $line"
    done < /path/to/file.txt
  • IFS= read -r line ensures that each line is read correctly, even if it contains spaces or other special characters.

  • The loop will process each line of the file until the end of the file is reached.

    Example 4: Infinite Loop

    An infinite loop continues indefinitely until interrupted (e.g., with Ctrl+C). This can be useful in situations where you need continuous operation:

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

    while true
    do
    echo "This is an infinite loop. Press Ctrl+C to stop."
    sleep 2
    done

    This loop will print the message every 2 seconds until manually stopped.

    Summary

  • while loops are great for situations where you need to repeat a task until a specific condition is met.

  • They’re commonly used for waiting for conditions, processing files, and other tasks where the number of iterations isn’t predetermined.

Understanding while loops will help you write more flexible and responsive Bash scripts.