If you’re a developer or sysadmin working with Bash scripts, you’re probably familiar with the
while loops. But have you ever used the
until loop? This lesser-known looping construct can be just as powerful and useful as its more popular counterparts. In this blog, we’ll explore the basics of
until loops in Bash and give you some tips and examples to help you incorporate them into your workflow.
Requirements and Dependencies
until loops in Bash, you’ll need a Unix-like operating system with the Bash shell installed. This could be a Linux distribution, macOS, or even Windows with a Bash emulator like Cygwin or WSL. You’ll also need some basic knowledge of Bash scripting and looping constructs.
until Loop in Action
until loop is similar to the
while loop, but with one key difference: the loop continues to execute until the specified condition is met. In other words, the loop will run as long as the condition is
false. Here’s the basic syntax:
until [ condition ]
# loop body
Let’s take a look at an example. Suppose we want to create a script that checks the status of the website itvraag.nl every 5 seconds until it returns a
200 OK status code. We can use the
curl command to check the status, and the
sleep command to pause for 5 seconds between checks. Here’s what the script might look like:
until curl -I itvraag.nl | grep "200 OK" > /dev/null
echo "Site is down, trying again in 5 seconds..."
echo "Site is up!"
This script will keep checking the status of the website until it returns a
200 OK code, at which point it will print “Site is up!” and exit the loop.
Did you know that you can also use
until loops as infinite loops? All you have to do is specify a condition that is always
false, like this:
# loop body
This loop will run indefinitely, until you manually break out of it using the
break command or by killing the script.
untilloops are similar to
whileloops, but they continue to execute until the specified condition is met.
- You can use
untilloops to repeat a task until a certain condition is met, or as infinite loops.
Examples and Tips
Here are a few examples and tips to help you get started with
until loops in Bash:
untilloops to check the status of a server or service, and alert you when it comes back online.
untilloops to retry a task that might fail due to temporary issues, like network outages or server downtime.
untilloops to wait for a file to be created or modified, and then perform some action on it.
untilloops to repeat a task at regular intervals, like checking the status of a website every 5 minutes.
untilloops to create interactive menus or prompts for your Bash scripts.
Here’s a challenge for you: try creating a script that uses an
until loop to check the status of a server every 5 minutes, and sends an email notification if the server is down for more than 20 minutes. Good luck!