Bash While Loop
Bash While Loop is a loop statement used to execute a block of statements repeatedly based on the boolean result of an expression, for as long as the expression evaluates to TRUE.
A Bash while loop is useful when the number of repetitions is not known before the loop starts. For example, you can keep reading user input until the user enters a valid value, process lines from a file until the file ends, retry a command until it succeeds, or increment a counter until a condition becomes false.
How a Bash while loop checks its condition
The while loop checks the condition before every iteration. If the condition returns a successful exit status, the commands inside the loop are executed. After the commands finish, Bash checks the condition again. The loop stops when the condition fails.
In Bash, a condition is usually written with [ ] or [[ ]]. Use [ ] for simple POSIX-style tests. Use [[ ]] when you need Bash features such as compound conditions with && and ||, pattern matching, or safer string comparisons.
Syntax – Bash While Loop
while [ expression ]; do
statement(s)
done
The expression can contain only one condition. If the expression should have multiple conditions, the syntax of while loop is as follows :
while [[ expression ]]; do
statement(s)
done
The keyword do marks the start of the loop body, and done marks the end of the loop. The condition must be written carefully because a while loop can run forever if the value used in the condition is never changed inside the loop.
Bash while loop syntax using a counter
A counter-based while loop starts with an initial value, checks the value in the condition, and then updates the counter inside the loop body. This pattern is useful when you want a while loop to run a fixed number of times.
counter=1
while [ $counter -le limit ]; do
commands
((counter++))
done
For numeric comparisons in [ ], common operators are -lt for less than, -le for less than or equal to, -gt for greater than, -ge for greater than or equal to, -eq for equal to, and -ne for not equal to.
Example 1 – Bash While Loop
In this example, we are using while loop to execute a block of statements 10 times, and we print the iteration number in the while body.
Bash Script File
#!/bin/bash
count=10
i=0
# while loop
while [ $i -lt $count ]; do
echo "$i"
let i++
done
When the above while loop script is run in terminal, we will get the following output.
Output
$ ./bash-while-loop-example
0
1
2
3
4
5
6
7
8
9
Here, the variable i starts from 0. The loop continues while i is less than count. After every iteration, i is incremented. When i becomes 10, the condition [ $i -lt $count ] becomes false and the loop ends.
Example 2 – Bash While Loop – Multiple Conditions
In this example, we will write while loop with a compound condition consisting of simple conditions. The simple conditions are joined by Logical Operators.
Bash Script File
#!/bin/bash
count=10
a=0
b=0
# multiple conditions in the expression of while loop
while [[ $a -lt $count && $b -lt 4 ]]; do
echo "$a"
let a++
let b++
done
Run the above while loop script in terminal, and we shall get the following output.
Output
$ ./bash-while-loop-example
0
1
2
3
The loop stops after printing 3 because the second condition $b -lt 4 becomes false when b reaches 4. Even though a is still less than count, both conditions must be true because the loop uses the logical AND operator &&.
Bash while loop with user input
A while loop can keep asking for input until the user enters an expected value. The following script continues until the user types yes.
#!/bin/bash
answer=""
while [[ "$answer" != "yes" ]]; do
read -p "Type yes to continue: " answer
done
echo "You entered yes."
Quote string variables inside the condition. Quoting helps avoid errors when the variable is empty or contains spaces.
Type yes to continue: no
Type yes to continue: y
Type yes to continue: yes
You entered yes.
Bash while loop to read a file line by line
One common use of a while loop in Bash scripting is reading a text file line by line. This is useful for processing logs, lists of filenames, configuration values, or CSV-like text files.
Assume that names.txt contains the following lines.
Apple
Banana
Cherry
The following Bash script reads each line from the file and prints it.
#!/bin/bash
while IFS= read -r line; do
echo "Item: $line"
done < names.txt
Item: Apple
Item: Banana
Item: Cherry
The IFS= part prevents leading and trailing whitespace from being trimmed. The -r option prevents backslashes from being treated as escape characters. This form is safer for general line-by-line file reading.
Bash infinite while loop with break condition
An infinite while loop is written with true as the condition. Use this pattern only when you have a clear break condition inside the loop.
#!/bin/bash
while true; do
read -p "Enter a number greater than 10: " number
if [[ $number -gt 10 ]]; then
echo "Accepted: $number"
break
fi
echo "Try again."
done
Without the break statement, the loop would continue forever. Infinite while loops are often used for menus, retry logic, background checks, and interactive command-line scripts.
Single-line Bash while loop syntax
A while loop can also be written on a single line. This is useful for quick terminal commands, but longer scripts are usually easier to read when written across multiple lines.
while [ condition ]; do command1; command2; done
The following one-line loop prints numbers from 1 to 5.
i=1; while [ $i -le 5 ]; do echo "$i"; ((i++)); done
1
2
3
4
5
Using break and continue inside a Bash while loop
The break statement exits the while loop immediately. The continue statement skips the rest of the current iteration and moves to the next condition check.
#!/bin/bash
i=0
while [ $i -lt 6 ]; do
((i++))
if [ $i -eq 3 ]; then
continue
fi
if [ $i -eq 5 ]; then
break
fi
echo "$i"
done
1
2
4
In this script, 3 is skipped because of continue, and the loop stops when i becomes 5.
Common mistakes in Bash while loop conditions
| Mistake | Why it matters | Safer approach |
|---|---|---|
| Not updating the counter | The loop may never end. | Increment or modify the variable used in the condition. |
| Using string operators for numbers | Numeric comparisons may not work as intended. | Use -lt, -le, -gt, -ge, -eq, or -ne. |
| Leaving variables unquoted in string tests | Empty values or spaces can cause unexpected results. | Use quotes, for example [[ "$name" != "admin" ]]. |
| Forgetting spaces around brackets | [ is treated like a command in Bash syntax. | Write [ $i -lt 10 ], not [$i -lt 10]. |
Using [ ] for complex Bash conditions | Compound expressions can become harder to write correctly. | Use [[ ]] for multiple Bash conditions. |
We can also use Bash For loop for looping.
When to use Bash while loop instead of Bash for loop
Use a Bash while loop when the loop should continue until a condition changes. Use a Bash for loop when you already have a fixed list of values, filenames, words, or numbers to iterate over.
| Use while loop when | Use for loop when |
|---|---|
| You do not know the number of iterations in advance. | You have a known list of items. |
| You are waiting for valid user input. | You are looping through command arguments. |
| You are reading a file line by line. | You are processing files matched by a pattern. |
| You need retry logic based on a command result. | You need a simple loop over a range or list. |
QA checklist for Bash while loop examples
- Check that every while loop has a condition that can eventually become false, unless it intentionally uses
while true. - Confirm that counter variables are initialised before the loop and updated inside the loop.
- Use
[[ ]]for compound Bash conditions with&&or||. - Quote variables in string comparisons, especially when values may be empty or contain spaces.
- Test file-reading loops with blank lines, spaces, and backslashes if the script processes real text files.
FAQs on Bash while loop syntax and examples
What is a Bash while loop used for?
A Bash while loop is used to repeat commands while a condition is true. It is commonly used for counters, input validation, reading files line by line, retrying commands, and menu-style shell scripts.
How do I stop an infinite while loop in Bash?
Use a break statement inside the loop when the required condition is met. If a loop is already running in the terminal and you need to stop it manually, press Ctrl+C.
Should I use single brackets or double brackets in a Bash while loop?
Use [ ] for simple tests and [[ ]] for Bash-specific conditions, especially when combining multiple conditions with && or ||. Double brackets are often clearer for Bash scripts.
How do I read a file line by line using a Bash while loop?
Use while IFS= read -r line; do ... done < filename. This form reads each line safely without trimming whitespace or treating backslashes as escape characters.
Why is my Bash while loop not ending?
The loop usually does not end because the condition remains true. Check whether the variable used in the condition is updated inside the loop, and confirm that the comparison operator matches the type of value being tested.
Summary of Bash while loop usage
In this Bash Tutorial – Bash While Loop, we have learnt about syntax of while loop statement in bash scripting for single and multiple conditions in expression with example scripts. We also covered counter loops, user input loops, file-reading loops, infinite loops with break, one-line while loop syntax, continue, and common while loop mistakes.
TutorialKart.com