In Bash, the while
loop repeatedly executes a block of code as long as a condition is true. It is commonly used when the number of iterations is not known in advance. Here’s the basic syntax of a while
loop in Bash:
while [ condition ]; do
# Code to execute
done
The loop continues executing the code block as long as the condition
remains true. Once the condition
becomes false, the loop terminates, and the program execution continues with the next statement after the loop.
Here’s an example that demonstrates the usage of a while
loop in Bash:
#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
((count++))
done
In this example, the while
loop starts with an initial value of count
set to 1. The condition [ $count -le 5 ]
checks if the value of count
is less than or equal to 5. As long as this condition is true, the loop executes the code block, which consists of printing the value of count
and incrementing it by 1 using ((count++))
.
When you run this script, it will output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
The loop iterates five times, printing the value of count
from 1 to 5.
You can modify the condition
inside the while
loop to suit your specific needs. It can involve comparisons, logical operators, or checks against variables, allowing you to control the loop based on your requirements.