In shell scripting, a while
loop is used to repeatedly execute a block of code as long as a specified condition is true. Here's the basic syntax of a while
loop:
while [ condition ]; do
# Code to execute while the condition is true
done
Here's how it works:
condition
is evaluated.condition
is true (returns a zero exit status), the code block inside the while
loop is executed.condition
is evaluated again.condition
is still true, the code block is executed again.condition
becomes false (returns a non-zero exit status), at which point the while
loop terminates, and the script continues with the next command after the done
statement.Here's an example of a while
loop that counts from 1 to 5:
#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
((count++))
done
In this script:
count
variable is initialized to 1.while
loop checks whether $count
is less than or equal to 5.count
and increments it by 1 using ((count++))
.count
is no longer less than or equal to 5.You can also use break
statements within a while
loop to exit the loop prematurely based on certain conditions. Here's an example:
#!/bin/bash
count=1
while true; do
echo "Count: $count"
((count++))
if [ $count -gt 5 ]; then
break # Exit the loop when count is greater than 5
fi
done
In this script, we use while true
to create an infinite loop and then use an if
statement with the break
command to exit the loop when count
becomes greater than 5.
While loops are useful for scenarios where you need to repeat a task until a specific condition is met, such as reading lines from a file, processing user input, or waiting for a specific event to occur.
Here is a simple example which shows that loop terminates as soon as a becomes 6 −