Knowledgebase

Find frequently asked questions and setup guides by searching or by browsing the categories.

The Syntax

while condition; do
    commands
done

The condition is any command. Bash runs it before every pass: if it exits with status 0, the body runs; otherwise the loop ends. Usually the condition is a test in brackets, as explained in Bash if statement.

A Counter Loop

#!/bin/bash
i=1
while [ "$i" -le 5 ]; do
    echo "Pass $i"
    i=$((i + 1))
done

If you forget to change the variable, the loop never ends; stop it with Ctrl+C. For a fixed range or a list, a Bash for loop is shorter.

Read a File Line by Line

while IFS= read -r line; do
    printf '%s\n' "$line"
done < servers.txt
  • IFS=: keeps spaces at the start and end of each line.
  • -r: keeps backslashes as they are.
  • < servers.txt: after done, feeds the file to the whole loop.

If the last line of the file has no line break, read still fills the variable but reports failure, so the loop ends before handling that line. Write the first line as while IFS= read -r line || [ -n "$line" ]; do to keep it. read can also split a line into fields. This prints each account and its shell from /etc/passwd:

while IFS=: read -r name _ _ _ _ _ shell; do
    echo "$name uses $shell"
done < /etc/passwd

Why a Pipe Loses Your Variables

count=0
cat servers.txt | while read -r line; do
    count=$((count + 1))
done
echo "$count"    # prints 0

Each part of a pipeline runs in a subshell, so the loop changes its own copy of count, and the copy disappears when the loop ends. Redirect the file into the loop as shown above or, when the input comes from a command, use process substitution:

count=0
while read -r line; do
    count=$((count + 1))
done < <(grep -v '^#' servers.txt)
echo "$count"

A command inside the loop that reads standard input, such as ssh, swallows the rest of the file. Give it -n or < /dev/null, as described in /dev/null in Linux.

An Endless Loop with sleep

while true; do
    uptime >> /tmp/load.log
    sleep 60
done

Always put a sleep in an endless loop, or it keeps one CPU core busy. For a job that must survive logout and reboots, a systemd timer or a cron job is usually the better choice.

until: Run Until a Command Succeeds

until repeats while the condition fails and stops as soon as it succeeds. This waits up to a minute for a database port:

tries=0
until nc -z 127.0.0.1 5432; do
    tries=$((tries + 1))
    if [ "$tries" -ge 30 ]; then
        echo "Database did not start" >&2
        exit 1
    fi
    sleep 2
done
echo "Port 5432 is open"

nc comes from a netcat package: netcat-openbsd on Debian and Ubuntu, nmap-ncat on AlmaLinux and Rocky Linux. Both accept -z. Waiting for a file works the same way with a while loop and a negated test; the tests themselves are in Bash: check if a file exists.

while [ ! -f /run/myapp/ready ]; do
    sleep 1
done

break and continue

while IFS= read -r host; do
    [ -z "$host" ] && continue
    [ "$host" = "stop" ] && break
    ping -c 1 -W 2 "$host" > /dev/null && echo "$host is up"
done < hosts.txt

continue skips to the next pass, here for empty lines. break leaves the loop at once. Both take a number for nested loops; see Bash continue and break.

The One-Line Form

while true; do clear; df -h /; sleep 5; done

Semicolons replace the line breaks. For repeating a single command on screen, watch -n 5 df -h / does the same job.

Was this answer helpful?
Loading...