In Bash, the until
loop is similar to the while
loop, but it repeatedly executes a block of code as long as a condition is false. It is useful when you want to execute a loop until a particular condition becomes true. Here’s the basic syntax of an until
loop in Bash:
until [ condition ]; do
# Code to execute
done
The loop continues executing the code block as long as the condition
remains false. Once the condition
becomes true, the loop terminates, and the program execution continues with the next statement after the loop.
Here’s an example that demonstrates the usage of an until
loop in Bash:
#!/bin/bash
count=1
until [ $count -gt 5 ]; do
echo "Count: $count"
((count++))
done
In this example, the until
loop starts with an initial value of count
set to 1. The condition [ $count -gt 5 ]
checks if the value of count
is greater than 5. Since the initial value of count
is not greater than 5, 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, similar to the while
loop example.
The until
loop can be handy when you want to execute a block of code until a specific condition becomes true. You can modify the condition
inside the until
loop to suit your specific needs and control the loop based on your requirements.