Linux while Loops in Shell Scripts
Learn Linux and Bash while loops: syntax, conditions, numeric comparisons, counters, arithmetic updates, infinite-loop troubleshooting, and practical examples.
A while loop is a shell control structure that repeats a group of commands while a condition is true. The shell tests the condition before every iteration. If the condition is true, the loop body runs; when the condition becomes false, the loop stops.
While loops are useful when the number of repetitions depends on a changing value, user input, a file, or another condition rather than a predetermined list.
Basic while-loop syntax
The general structure places the test after while, starts the command body with do, and closes the body with done:
while condition
do
commands
done
The spaces before do and done are only for readability. A commonly formatted version is:
while condition; do
commands
done
The semicolon separates the condition from do when they are on the same line. The commands between do and done are the loop body. The condition is evaluated before each iteration, including the first one.
| Element | Role | Example usage |
|---|---|---|
while | Begins the loop and introduces its condition. | while [ "$count" -lt 5 ] |
| Conditional test | Returns true or false before each iteration. | [ "$count" -lt 5 ] |
do | Begins the command body. | do |
| Loop body commands | Commands executed while the condition is true. | echo "Working" |
done | Ends the loop body. | done |
Conditional expressions and square brackets
A condition is a test evaluated before each loop iteration. One common shell form uses square brackets, which are a command-like form of the test command:
[ "$count" -lt 5 ]
The -lt operator means “less than.” Square brackets require spaces on both sides: after the opening bracket and before the closing bracket. These forms are invalid or unreliable:
["$count" -lt 5]
[ "$count" -lt 5]
A shell variable is referenced with a dollar sign, such as $count. This process is called variable expansion: the shell substitutes the variable's current value before running the test. Quoting a variable, as in "$count", helps preserve it as one value and avoids problems when it is empty or contains whitespace.
Numeric comparison operators
| Operator | Meaning | Example condition |
|---|---|---|
-lt | Less than | [ "$n" -lt 5 ] |
-le | Less than or equal to | [ "$n" -le 5 ] |
-eq | Equal to | [ "$n" -eq 5 ] |
-ne | Not equal to | [ "$n" -ne 5 ] |
-gt | Greater than | [ "$n" -gt 5 ] |
-ge | Greater than or equal to | [ "$n" -ge 5 ] |
These operators are for integer comparisons. They are different from operators used for comparing strings or from arithmetic operators used inside arithmetic expressions.
Counter-controlled while loop
A counter-controlled loop initializes an integer variable before the loop, checks it against a limit, displays its value, and changes it inside the body:
#!/usr/bin/env bash
count=0
while [ "$count" -lt 5 ]; do
echo "The counter is $count"
let count=count+1
done
The assignment count=0 initializes the variable. Shell assignments must not contain spaces around the equals sign. The loop continues while count is less than five. Each iteration prints the current value, then let count=count+1 increases it by one.
The output is:
The counter is 0
The counter is 1
The counter is 2
The counter is 3
The counter is 4
The value five is not printed because -lt 5 means strictly less than five. After the iteration that prints four, the counter becomes five. The next test is false, so the body does not run again.
Updating state inside a loop
Most useful while loops need some changing state: a counter, incoming input, a file position, or an external condition. If the controlling state never changes, the condition may remain true forever, creating an infinite loop.
let is a Bash and Korn shell builtin for evaluating arithmetic expressions. In Bash, arithmetic expansion is another widely used style:
#!/usr/bin/env bash
count=0
while [ "$count" -lt 5 ]; do
echo "The counter is $count"
((count++))
done
The expression ((count++)) increments count after its current value is used. This example has the same output sequence, zero through four. Arithmetic expansion generally refers to the shell's arithmetic syntax using double parentheses, such as $((count + 1)); the arithmetic command form ((count++)) is commonly used for updates in Bash scripts.
Running a while loop in a script or shell
Place the loop in a script file and choose an interpreter with a shebang, the first line beginning with #!. The examples using ((...)) and Bash-specific behavior should select Bash:
#!/usr/bin/env bash
limit=3
n=0
while [ "$n" -lt "$limit" ]; do
echo "Step $n"
((n++))
done
After saving the file, make it executable and run it:
chmod +x loop.sh
./loop.sh
The same basic construct can be entered interactively. Type the lines at a shell prompt and finish with done:
n=0
while [ "$n" -lt 3 ]; do
echo "$n"
((n++))
done
For portable POSIX-style shell scripts, use syntax supported by the selected shell. For Bash-specific syntax and arithmetic, use a Bash shebang and run the script with Bash. See Bourne Again Shell (Bash) for more Bash fundamentals.
One-line while loops
Semicolons separate shell commands when several commands appear on one line:
n=0; while [ "$n" -lt 3 ]; do echo "$n"; ((n++)); done
Multiline formatting is usually easier to read, edit, and troubleshoot. The one-line form is useful for short interactive experiments.
Troubleshooting while loops
The loop never stops
Check whether the counter or other controlling state changes on every iteration. Also verify that the update moves the value toward the stopping condition and that the comparison operator matches the intended rule.
# Infinite: n never changes
n=0
while [ "$n" -lt 3 ]; do
echo "$n"
done
When an accidental infinite loop is running interactively, press Ctrl+C to interrupt it. Then check the initial value, condition, update expression, and boundary.
The test expression produces an error
- Use spaces around the square brackets and comparison operator.
- Initialize a variable before testing it.
- Use a numeric value with numeric operators such as
-lt. - Validate or constrain input before using it in a numeric comparison.
For example, count= leaves the variable empty. An empty or nonnumeric value can make a numeric test invalid or produce unexpected behavior.
The loop runs one time too many or too few
Compare the desired endpoint with the operator. Use -lt for an exclusive upper limit, so a limit of five produces zero through four. Use -le when the limit itself should be included. Also check whether the counter is incremented before or after the output command.
Exam-relevant points
- A while loop tests its condition before every iteration.
- The body runs only while the condition evaluates as true.
dobegins the body anddoneends it.- Square brackets in a test expression need spaces around their contents.
-ltmeans numeric “less than,” not less than or equal to.- Variables expand when referenced with a dollar sign, such as
$count. - A loop needs changing state or another changing condition to terminate.
- Use a Bash shebang when the script depends on Bash-specific arithmetic syntax.