Bash While Loop
Introduction
One of the most fundamental ideas in programming languages is the loop. When you want to perform a series of commands repeatedly until a certain condition is met, loops come in handy.
Loops are useful for automating repeated operations in scripting languages like Bash. In Bash scripting, there are three basic loop constructs: for
loop, while
loop, and until
loop.
The fundamentals of while
loops in Bash are covered in this tutorial. We will also address a few FAQs on Bash While Loop.
Bash while
Loop
The while
loop is used to repeat a series of commands an unknown number of times as long as the condition is true.
The Bash while
loop is written as follows:
while [CONDITION]
do
[COMMANDS]
done
The while
keyword is followed by the conditional phrase in the while
statement.
Before the orders are executed, the condition is evaluated. Commands are performed if the condition evaluates to true. If the condition evaluates to false, the loop will be ended, and program control will be given to the next command.
The current value of the variable i
is reported and incremented by one in the example below on each iteration.
i=0
while [ $i -le 2 ]
do
echo Number: $i
((i++))
done
As long as i
is less than or equal to two, the Tue loop iterates. It will give you the following results:
Output
Number: 0
Number: 1
Number: 2
Infinite while
Loop
An endless loop is a loop that never ends and repeats indefinitely. You have an infinite loop if the condition always evaluates to true.
The built-in command :
is used to generate an infinite loop in the following example. :
always returns true. The true
built-in or any other statement that always returns true can also be used.
while :
do
echo "Press <CTRL+C> to exit."
sleep 1
done
The while loop will continue to run indefinitely. By using CTRL+C
, you can end the loop.
Here's a single-line version:
while :; do echo 'Press <CTRL+C> to exit.'; sleep 1; done
Read a File Line By Line
Reading a file, data stream, or variable line by line is one of the most common uses of the while
loop.
Here's an example of reading and printing each line from the /etc/passwd
file:
file=/etc/passwd
while read -r line; do
echo $line
done < "$file"
Instead of using a condition to control the while
loop, we use input redirection (< "$file"
) to send a file to the read
command, which controls the loop. The while
loop will continue to execute until the last line has been read.
To prevent backslash from acting as an escape character when reading a file line by line, always use read
with the -r
option.
The read
command cuts the starting and trailing whitespace characters by default (spaces and tabs). To avoid this, use the IFS=
option before reading:
file=/etc/passwd
while IFS= read -r line; do
echo $line
done < "$file"
break
and continue
Statements
The while loop can be controlled with the break and continue commands.
break
Statement
The break
statement ends the current loop and transfers program control to the command that comes after it. When a given condition is met, it is frequently used to end the loop.
When the current iterated item equals 2
, the loop will be interrupted, as seen in the following example.
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
command ends the current loop iteration and moves program control to the next loop iteration.
Once the current iterated item equals 2
, the continue
statement causes execution to return to the beginning of the loop and continue with the next iteration as seen below.
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!
FAQs on Bash While Loop
Can I use variables in the while
loop's condition?
Yes, you can use variables in the while
loop's condition. The variable's value is evaluated for each iteration, and the loop continues as long as the condition evaluates to true.
How do I exit or terminate a while
loop prematurely?
To exit or terminate a while
loop prematurely, you can use the break
statement. When encountered, the break
statement transfers control to the first line after the loop.
How do I skip the rest of the current iteration in a while
loop?
To skip the remaining code in the current iteration and start the next iteration immediately, you can use the continue
statement. When encountered, the continue
statement transfers control to the loop condition.
Can I use multiple conditions in a while
loop?
Yes, you can use multiple conditions in a while
loop by combining them using logical operators such as &&
(AND) or ||
(OR). The loop continues until all conditions are true (with &&
) or at least one condition is true (with ||
).
Can I modify the looping variable inside the while
loop?
Yes, you can modify the looping variable inside the while
loop. However, it's important to ensure the loop's termination condition is eventually met, or else you risk creating an infinite loop.
How can I simulate a countdown or a reverse loop using a while
loop?
To simulate a countdown or a reverse loop, you can use a decrementing variable as part of the condition. For example: counter=10; while (( counter > 0 )); do echo $counter; (( counter-- )); done
Can I use nested while
loops in Bash?
Yes, you can use nested while
loops in Bash. Nested loops allow you to perform more complex iterations or repeated tasks within each iteration of another loop.
Conclusion
The while
loops execute a series of commands periodically as long as a condition is true.
If you have any queries, please leave a comment below and we’ll be happy to respond to them.