On this page
In our previous article, we explored the for
loop construct in Bash scripting, which allows you to iterate over a sequence of values. However, Bash offers another powerful loop construct known as the while
loop, designed to execute a set of commands repeatedly as long as a specified condition remains true. This article will cover the Bash while
loop, exploring its syntax, usage, and of course, some practical examples.
bash while loop
The bash while loop is designed to execute a block of code repeatedly as long as a specified condition holds true.The basic syntax of the while
loop is as follows:
while [ condition ]
do
# Code to be executed
done
Let's break down this structure:
- The
while
keyword initiates the loop. [ condition ]
is the condition that is evaluated before each iteration of the loop. If the condition is true, the commands within the loop body are executed. If the condition is false, the loop terminates.- The
do
keyword signifies the beginning of the code block to be repeated. - The actual code to be executed resides between
do
anddone
. - The
done
keyword marks the end of the loop body.
Let's consider a simple example that demonstrates the usage of the while
loop:
#!/bin/bash
counter=1
while [ $counter -le 5 ]
do
echo "Counter: $counter"
((counter++))
done
In this example, the while
loop iterates over a counter variable, starting from 1 and incrementing it by 1 after each iteration until it reaches 6. The condition [ $counter -le 5 ]
checks if the counter is less than or equal to 5. If the condition is true, the loop body is executed, printing the current value of the counter and incrementing it. Once the counter exceeds 5, the loop terminates.
while
loop is evaluated before each iteration. This means that if the condition is false initially, the loop body will not be executed at all.Infinity while loop
In some cases, you might want to create an infinite loop that runs indefinitely until a specific condition is met or until the loop is explicitly terminated. This can be achieved by using a condition that is always true, such as true
or a non-zero value.
In the following example, the while
loop runs indefinitely because the condition true
is always evaluated as true. However, to prevent an endless loop, we introduce an if
statement within the loop body that checks if the counter exceeds 10. If the condition is met, the break
statement is executed, terminating the loop.
#!/bin/bash
counter=1
while true
do
echo "Counter: $counter"
((counter++))
if [ $counter -gt 10 ]
then
break
fi
done
You may also see some bash scripts that use the shorthand syntax for infinity loops.
while :
do
# Code to be executed
done
break and continue statement
The break
and continue
statements are used to control the flow of execution within loops in Bash. They provide a way to alter the normal loop behavior based on specific conditions.
break statement
The break
statement is used to exit or terminate a loop prematurely. When encountered within a loop, the break
statement immediately stops the loop's execution and transfers control to the next statement following the loop.
Using the same code as above, the while
loop runs indefinitely due to the true
condition. However, when the counter exceeds 5, the break
statement is executed, terminating the loop. The program then proceeds to execute the next statement, which is echo "Loop terminated."
.
#!/bin/bash
counter=1
while true
do
echo "Counter: $counter"
((counter++))
if [ $counter -gt 5 ]
then
break
fi
done
echo "Loop terminated."
continue statement
The continue
statement is used to skip the remaining commands in the current iteration of a loop and move to the next iteration. It is typically used in conjunction with an if
statement to selectively skip certain iterations based on a specific condition.
Here's an example that demonstrates the usage of the continue
statement:
#!/bin/bash
counter=1
while [ $counter -le 10 ]
do
((counter++))
if [ $((counter % 2)) -eq 0 ]
then
continue
fi
echo "Counter: $counter"
done
In this example, the while
loop iterates from 1 to 10. Within the loop, the if
statement checks if the counter is an even number using the modulus operator %
. If the counter is even, the continue
statement is executed, skipping the remaining commands in the current iteration and moving to the next iteration. However, if the counter is odd, the loop body executes, and the current value of the counter is printed.
Read a file using a while loop
One common use case for the while
loop is reading data from a file line by line. This can be achieved by combining the while
loop with the read
command.
Here is an example:
#!/bin/bash
while IFS= read -r line
do
# Process each line
echo "Processing: $line"
done < "data.txt"
In this example, the while
loop is used in conjunction with the read
command to read each line from the specified file (data.txt
). The read
command reads a line of input and assigns it to the variable line
. The -r
option prevents backslash from acting as an escape character.
Before the read
command, we set IFS=
(IFS stands for Internal Field Separator). By default, the read
command trims leading and trailing whitespace characters (spaces and tabs). Setting IFS=
prevents this behavior, ensuring that leading/trailing whitespace is preserved.
< "data.txt"
syntax is known as a redirection operator, which redirects the contents of the file data.txt
as input to the read
command within the while
loop.Here is another method of reading files using pipes:
cat data.txt | while read line
do
# Process each line
echo "Processing: $line"
done
Conclusion
The Bash while
loop is a construct that allows executing commands repeatedly based on a specified condition. This article covered the loop's syntax, control statements like break
and continue
, and practical examples like reading files line by line. This knowledge should help you automate boring tasks and as well improve your scripting skills.