while - macOS


Overview

while is a command-line utility that executes a set of commands repeatedly until a condition is met. It is commonly used in shell scripting to automate repetitive tasks.

Syntax

while <condition>
do
    <command(s)>
done

Arguments:

  • condition: A test expression that evaluates to true or false.
  • command(s): Commands to be executed when the condition is true.

Options/Flags

None

Examples

Simple Example:

while true; do echo "Hello, world!"; sleep 1; done

This command will print “Hello, world!” repeatedly until the user terminates it with Ctrl+C.

Complex Example:

while read line
do
    if [[ $line == "exit" ]]; then
        break
    fi
    echo $line
done < input.txt

This command reads lines from input.txt and prints them until the line “exit” is encountered.

Common Issues

Infinite Loop:

If the condition is always true, the while loop will run indefinitely. Use break to exit the loop when necessary.

Incorrect Condition:

Ensure the condition is written correctly and evaluates to a boolean value (true or false).

Integration

With Pipes:

ls -l | while read line; do echo $line >> output.txt; done

This command lists files and directories recursively and writes their details to output.txt.

With Other Commands:

while [[ $(df / | tail -1 | awk '{print $5}') -gt "90%" ]]
do
    df /
    sleep 60
done

This command repeatedly checks disk space usage and logs the result every minute.

  • until: Executes commands until the condition is met.
  • for: Iterates over a range of values.
  • case: Executes commands based on matching patterns.