Bash while loops explained banner
Bash focus guide

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.

On this page
Basics

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
Use a 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.
Counting

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
$ bash counter.sh
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5

The line ((count++)) increases the value of count on each loop. Without it, the condition never changes and the loop will keep running.

Tests

Common while loop conditions

Most while loops depend on a test. These are the common operators you will use in beginner Bash scripts.

ConditionMeaningExample
-eqNumber equals[ "$count" -eq 5 ]
-neNumber does not equal[ "$count" -ne 0 ]
-ltNumber is less than[ "$count" -lt 10 ]
-leNumber is less than or equal to[ "$count" -le 10 ]
-gtNumber 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.

Choosing the right loop

When should you use a while loop instead of a for loop?

Use caseBetter loopWhy
Loop through a fixed list of filesforThe list is already known.
Keep asking until the user enters qwhileThe number of repeats depends on user input.
Wait until a website respondswhile or untilThe script stops when the condition changes.
Read a file line by linewhile readIt safely processes each line as input.

If you want fixed-list examples, read Bash for loops explained.

Monitoring loops

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
$ bash forever.sh
Still running...
Still running...
Still running...
Always add 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.
Files

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
$ bash read-domains.sh
Processing: example.com
Processing: example.org
Processing: commandlinequiz.com

The IFS= read -r form is safer than plain read line. It helps preserve spacing and stops backslashes being treated as escape characters.

Retries

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.

Practical script

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
$ bash website-monitor.sh
[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.com

For a fuller version with multiple URLs, logging and cron usage, read the Bash uptime monitor guide.

Alternative loop

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.

Troubleshooting

Common Bash while loop mistakes

MistakeProblemFix
while[$count -le 5]Missing spaces around [ and ].while [ "$count" -le 5 ]
Not changing the variableThe loop condition never becomes false.Use ((count++)) or another update inside the loop.
No sleep in a monitorThe loop can run constantly and waste CPU.Add a sensible sleep.
read lineCan handle backslashes and spacing badly.Use IFS= read -r line.
Unquoted variablesEmpty values or spaces can break tests.Use "$variable".
Practice

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.

Keep learning

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.

$ practise_next --topic bash

Practise this next

Turn the guide into practice with a related quiz, builder, cheat sheet or learning path.