Bash while Loop: Syntax and Examples

By 

Updated on

6 min read

Bash while loop syntax and examples in a shell script

Loops are one of the fundamental concepts of programming languages. Loops are handy when you want to run a series of commands a number of times until a particular condition is met. Before diving in, make sure you are familiar with the basic Linux commands .

In scripting languages such as Bash, loops are useful for automating repetitive tasks. There are three basic loop constructs in Bash scripting, for loop , while loop, and until loop .

This tutorial covers the basics of while loops in Bash. We will also show you how to use the break and continue statements to alter the flow of a loop.

while Loop Syntax

The while loop is used to perform a given set of commands an unknown number of times as long as the given condition evaluates to true.

The Bash while loop takes the following form:

txt
while [CONDITION]
do
  [COMMANDS]
done

The while statement starts with the while keyword, followed by the conditional expression.

The condition is evaluated before executing the commands. If the condition evaluates to true, commands are executed. Otherwise, if the condition evaluates to false, the loop is terminated, and the program control is passed to the command that follows.

In the example below, on each iteration, the current value of the variable i is printed and incremented by one. The condition uses the -le comparison operator to check if i is less than or equal to 2.

sh
i=0

while [ $i -le 2 ]
do
  echo Number: $i
  ((i++))
done

The loop iterates as long as i is less than or equal to two. It will produce the following output:

output
Number: 0
Number: 1
Number: 2

Infinite while Loop

An infinite loop is a loop that repeats indefinitely and never terminates. If the condition always evaluates to true, you get an infinite loop.

In the following example, we are using the built-in command : to create an infinite loop. : always returns true. You can also use the true built-in or any other statement that always returns true.

sh
while :
do
  echo "Press <CTRL+C> to exit."
  sleep 1
done

The while loop above will run indefinitely. You can terminate the loop by pressing CTRL+C.

Here is a single-line equivalent:

sh
while :; do echo 'Press <CTRL+C> to exit.'; sleep 1; done

Read a File Line By Line

One of the most common usages of the while loop is to read a file, data stream, or variable line by line.

Here is an example that reads the /etc/passwd file line by line and prints each line:

sh
file=/etc/passwd

while read -r line; do
  echo "$line"
done < "$file"

Instead of controlling the while loop with a condition, we are using input redirection (< "$file") to pass a file to the read command, which controls the loop. The while loop will run until the last line is read.

When reading file line by line, always use read with the -r option to prevent backslash from acting as an escape character.

By default, the read command trims the leading/trailing whitespace characters (spaces and tabs). Use the IFS= option before read to prevent this behavior:

sh
file=/etc/passwd

while IFS= read -r line; do
  echo "$line"
done < "$file"

break and continue Statements

The break and continue statements can be used to control the while loop execution.

break Statement

The break statement terminates the current loop and passes program control to the command that follows the terminated loop. It is usually used to terminate the loop when a certain condition is met.

In the following example, the execution of the loop will be interrupted once the current iterated item is equal to 2.

sh
i=0

while [ $i -lt 5 ]
do
  echo "Number: $i"
  ((i++))
  if [[ "$i" == '2' ]]; then
    break
  fi
done

echo 'All Done!'
output
Number: 0
Number: 1
All Done!

continue Statement

The continue statement exits the current iteration of a loop and passes program control to the next iteration of the loop.

In the following example, once the current iterated item is equal to 2 the continue statement will cause execution to return to the beginning of the loop and to continue with the next iteration.

sh
i=0

while [ $i -lt 5 ]
do
  ((i++))
  if [[ "$i" == '2' ]]; then
    continue
  fi
  echo "Number: $i"
done

echo 'All Done!'
output
Number: 1
Number: 3
Number: 4
Number: 5
All Done!

Quick Reference

PatternExample
Basic while loopwhile [ $i -le 10 ]; do ...; done
Infinite loopwhile :; do ...; done
Read file line by linewhile read -r line; do ...; done < file
Preserve whitespacewhile IFS= read -r line; do ...; done < file
Break on conditionif [[ ... ]]; then break; fi
Skip iterationif [[ ... ]]; then continue; fi

For a printable quick reference, see the bash cheatsheet .

Troubleshooting

Loop never terminates
Make sure the variable in the condition is updated inside the loop body and that the condition will eventually become false.

integer expression expected error
This usually means a numeric variable is empty or contains non-numeric text. Initialize counters before use, for example i=0.

Whitespace is lost when reading lines
Use IFS= read -r line and print with echo "$line" to preserve leading spaces and backslashes.

FAQ

What is the difference between while and until?
A while loop runs as long as the condition is true. An until loop runs as long as the condition is false — it is the logical opposite of while.

How do I exit an infinite while loop?
From the terminal, press CTRL+C to interrupt the loop. Inside the script, use a break statement inside an if block to exit when a condition is met.

Can I use while to loop a specific number of times?
Yes. Initialize a counter variable and increment it each iteration using ((i++)). Use a condition like [ $i -le 10 ] to control how many times the loop runs. See the increment and decrement guide for counter examples.

Why does my while loop not terminate?
The condition always evaluates to true. Check that the variable being tested is actually changing inside the loop body, and that the condition will eventually become false.

Can I nest while loops?
Yes. You can place a while loop inside another while loop. Use separate counter variables for each loop to avoid conflicts.

Conclusion

The while loop repeatedly executes a given set of commands as long as a condition is true. To learn more about running your scripts, see our guide on how to run a Bash script .

If you have any questions, feel free to leave a comment below.

Tags

Linuxize Weekly Newsletter

A quick weekly roundup of new tutorials, news, and tips.

About the authors

Dejan Panovski

Dejan Panovski

Dejan Panovski is the founder of Linuxize, an RHCSA-certified Linux system administrator and DevOps engineer based in Skopje, Macedonia. Author of 800+ Linux tutorials with 20+ years of experience turning complex Linux tasks into clear, reliable guides.

View author page