
Bash While Loops Explained
Bash while loops repeat commands while a condition is true. They are perfect for counters, menus, reading files line by line, retries, monitoring checks and scripts that need to wait for something to change.
Basic Bash while loop syntax
A while loop checks a condition before each run. If the condition is true, the commands run. When the condition becomes false, the loop stops.
while [ condition ]; do
command
done
You can also write it over multiple lines, which is easier to read in real scripts:
while [ condition ]
do
command
done
while loop when the condition controls how long the script should continue. Use a for loop when you already have a fixed list of things to process.Simple counter example
This script counts from 1 to 5.
#!/usr/bin/env bash
count=1
while [ "$count" -le 5 ]; do
echo "Count is: $count"
((count++))
done
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5The line ((count++)) increases the value of count on each loop. Without it, the condition never changes and the loop will keep running.
Common while loop conditions
Most while loops depend on a test. These are the common operators you will use in beginner Bash scripts.
| Condition | Meaning | Example |
|---|---|---|
-eq | Number equals | [ "$count" -eq 5 ] |
-ne | Number does not equal | [ "$count" -ne 0 ] |
-lt | Number is less than | [ "$count" -lt 10 ] |
-le | Number is less than or equal to | [ "$count" -le 10 ] |
-gt | Number is greater than | [ "$count" -gt 0 ] |
= | String equals | [ "$answer" = "yes" ] |
!= | String does not equal | [ "$choice" != "q" ] |
For a deeper look at these tests, see the Bash operators guide.
When should you use a while loop instead of a for loop?
| Use case | Better loop | Why |
|---|---|---|
| Loop through a fixed list of files | for | The list is already known. |
Keep asking until the user enters q | while | The number of repeats depends on user input. |
| Wait until a website responds | while or until | The script stops when the condition changes. |
| Read a file line by line | while read | It safely processes each line as input. |
If you want fixed-list examples, read Bash for loops explained.
Infinite while loops with while true
while true creates a loop that runs until you stop it, or until the script exits from inside the loop.
#!/usr/bin/env bash
while true; do
echo "Still running..."
sleep 5
done
Still running...
Still running...
Still running...sleep to monitoring loops. Without it, your script can run flat out and waste CPU. Bash will happily sprint into a wall if you let it.Read a file line by line safely
This is one of the most useful while loop patterns in Bash.
#!/usr/bin/env bash
while IFS= read -r line; do
echo "Processing: $line"
done < domains.txt
If domains.txt contains:
example.com
example.org
commandlinequiz.com
Processing: example.com
Processing: example.org
Processing: commandlinequiz.comThe IFS= read -r form is safer than plain read line. It helps preserve spacing and stops backslashes being treated as escape characters.
Retry a command until it works
This pattern is useful when a service, website or network check may not work immediately.
#!/usr/bin/env bash
attempt=1
max_attempts=5
while [ "$attempt" -le "$max_attempts" ]; do
echo "Attempt $attempt of $max_attempts"
if curl -fsS https://example.com > /dev/null; then
echo "Website responded successfully"
exit 0
fi
echo "Not ready yet, waiting..."
((attempt++))
sleep 10
done
echo "Website did not respond after $max_attempts attempts"
exit 1
This is safer than an endless loop because it has a clear limit and returns a useful exit code if the check fails.
Website status monitor with curl
This script checks a website every 30 seconds and prints the HTTP status code plus the response time.
#!/usr/bin/env bash
URL="https://example.com"
while true; do
result=$(curl -o /dev/null -s -w "%{http_code} %{time_total}" "$URL")
status=$(echo "$result" | awk '{print $1}')
time_total=$(echo "$result" | awk '{print $2}')
timestamp=$(date "+%Y-%m-%d %H:%M:%S")
if [ "$status" = "200" ]; then
echo "[$timestamp] OK $status ${time_total}s $URL"
else
echo "[$timestamp] WARN $status ${time_total}s $URL"
fi
sleep 30
done
[2026-05-05 11:15:01] OK 200 0.184921s https://example.com
[2026-05-05 11:15:31] OK 200 0.172311s https://example.com
[2026-05-05 11:16:01] WARN 500 0.341002s https://example.comFor a fuller version with multiple URLs, logging and cron usage, read the Bash uptime monitor guide.
while vs until
while runs while a condition is true. until runs until a condition becomes true.
#!/usr/bin/env bash
until curl -fsS https://example.com > /dev/null; do
echo "Waiting for website..."
sleep 10
done
echo "Website is responding"
This can read more naturally when you are waiting for something to become available.
Common Bash while loop mistakes
| Mistake | Problem | Fix |
|---|---|---|
while[$count -le 5] | Missing spaces around [ and ]. | while [ "$count" -le 5 ] |
| Not changing the variable | The loop condition never becomes false. | Use ((count++)) or another update inside the loop. |
No sleep in a monitor | The loop can run constantly and waste CPU. | Add a sensible sleep. |
read line | Can handle backslashes and spacing badly. | Use IFS= read -r line. |
| Unquoted variables | Empty values or spaces can break tests. | Use "$variable". |
Practice exercises
Countdown timer
Create a loop that counts down from 10 to 1 with a one second delay.
Domain checker
Read a list of domains from a file and run dig +short against each one.
Log writer
Modify the website monitor so it writes output to uptime.log.
Safe exit
Add a maximum retry limit to a loop that would otherwise run forever.
What should you learn next?
Once you understand while loops, the next step is combining them with arguments, user input, tests and real Linux commands. That is where Bash starts to feel less like syntax and more like automation.