Introduction
The three Bash loop constructs are for, while
, and until
. The until
loop is a crucial feature of Bash scripts that executes a code block repeatedly until a specific condition becomes true.
The functionality allows users to create scripts that automate repetitive tasks. The until
loop is handy when the condition for loop termination is less obvious or harder to determine at the outset.
In this tutorial, you will learn to use the until
loop in Bash with practical examples.
Prerequisites
- A system running Linux.
- Access to the terminal (Ctrl+Alt+T).
What is the until Loop in Bash?
The Bash until
loop is a control flow statement that allows a repeated code execution until a particular condition is met. Since the loop runs a block of code as long as the condition is false, it represents an inversion of the while
loop, which executes code as long as the condition is true.
The until
loop is useful when you need to wait for a specific condition to be fulfilled, such as a file to be created or a network service to become available. The loop can significantly simplify scriptwriting and facilitate your work.
until Loop Syntax Explained
The general syntax of an until
loop in Bash script is:
until [condition]
do
block of code
done
The [condition]
is a test or command that evaluates to true
or false
. If it is false, the code block inside the loop is executed repeatedly until the condition becomes true.
The [condition]
is checked before each loop iteration. If it is false, the script executes the commands within the loop. Once the [condition]
becomes true, the loop stops, and the control transfers to the next command line after the done
keyword.
Examples of until Loop in Bash
Below are some practical examples of using the until
loop. The examples involve using the loop in Bash scripts to help you understand how it works and how to use it.
Example 1: Basic Counting Loop
The following example shows how to use the until
loop to create a basic counting loop that counts from one to five. Follow the steps below:
1. Create a new Bash script using a text editor of your choice. For this tutorial, we will use nano:
nano basic-loop.sh
2. Edit the file and paste the following code:
#!/bin/bash
counter=0
until [ $counter -gt 5 ]
do
echo "Count: $counter"
((counter++))
done
3. Save the script and exit the file.
4. Make the script executable using chmod:
chmod +x basic-loop.sh
5. Run the script:
./basic-loop.sh
This script initializes a counter to 0 and increments it in each iteration of the loop. The loop continues until the counter is greater than 5.
Example 2: Waiting for a File to Exist
In this example, we create a script with an until
loop that keeps iterating the loop until a specified file is created. Once it finds the file in the specified location, the script breaks the loop and continues with the execution.
Follow the steps below:
1. Create a new script and paste the following code:
#!/bin/bash
file_path="/path/to/your/file"
until [ -f $file_path ]
do
echo "Waiting for the file to be created..."
sleep 1
done
echo "The file exists. Proceeding..."
Replace the "/path/to/your/file"
in the first line after the shebang with the path of the file you want to wait for.
2. Change the file permissions to make the script executable and then run the script:
The until
loop keeps checking if the file exists at a given path. Once the file is found, it prints a message, and the script continues.
Example 3: Check Network Connectivity
In the following example, we create a script that uses the until
loop to ping www.google.com repeatedly. The script keeps running until a successful ping response is received.
Follow the steps below:
1. Create a new script and paste the following code:
#!/bin/bash
until ping -c1 www.google.com &>/dev/null
do
echo "Waiting for www.google.com - network down?"
sleep 5
done
echo "Ping successful! www.google.com is reachable."
2. Save the script and make it executable.
3. Run the script:
The script pings www.google.com and continues to do so every 5 seconds until the ping is successful. You can use a script like this when checking network connectivity or waiting for a server to become available.
Example 4: Infinite Loop Using until
The following example is a script with an until
loop that runs infinitely. The condition is set to false
, so the loop doesn't stop running.
Warning: If you create a resource-demanding task and set it to loop infinitely, it can cause system instability and unresponsiveness or slow down the machine. When developing and testing scripts with loops, it's a good practice to have safeguards in place, such as limiting the number of iterations or adding a sleep command to avoid excessive CPU usage.
Follow the steps below:
1. Create a new script and paste the following code:
#!/bin/bash
## This is an infinite loop as the condition is set to false.
condition=false
iteration_no=0
until $condition
do
echo "Iteration no : $iteration_no"
((iteration_no++))
sleep 1
done
2. Save the script and make it executable.
3. Run the script:
The script keeps running until you manually break the loop using Ctrl+C.
Example 5: Using until with break and continue
The following example utilizes the until
loop in a Bash script that counts from 1 to 10 but skips the number 5 using the continue statement. The script exits the loop when the count reaches 8 using the break statement.
Follow the steps to test the script:
1. Create a new script and paste the following lines:
#!/bin/bash
count=1
until (( count > 10 ))
do
# Skip number 5 using the 'continue' statement
if (( count == 5 ))
then
(( count++ ))
continue
fi
echo "Count is $count"
# Exit the loop when count reaches 8 using the 'break' statement
if (( count == 8 ))
then
break
fi
(( count++ ))
done
echo "Loop finished!"
2. Save the script and make it executable.
3. Run the script:
The loop counts from 1 to 10 but skips the number 5 using continue
, and it stops executing when the count reaches 8 using break
.
Example 6: until Loop with Single Condition
The following example shows how to use the until
loop with a single condition. The script generates random numbers between 1 and 10 until it generates a number greater than 8.
Test the script by following the steps below:
1. Create a Bash script and paste the following lines:
#!/bin/bash
until (( num > 8 ))
do
# Generate a random number between 1 and 10
num=$(( (RANDOM % 10) + 1 ))
echo "Generated number: $num"
done
echo "Loop finished!"
2. Save the script and make it executable.
3. Run the script:
The loop generates random numbers until it generates a number greater than 8. In this example, the loop terminated when the number 9 was generated. The loop then prints "Loop finished!" and exits. The generated numbers vary with each execution due to the use of the RANDOM
variable.
Example 7: until Loop with Multiple Conditions
Like the previous example, this script also uses an until
loop. However, instead of one condition, it uses multiple conditions to perform different actions based on the counter value. The script counts from 1 to 10 and performs specific actions for specific numbers.
Follow these steps:
1. Create a script and paste the following lines:
#!/bin/bash
count=1
until (( count > 10 ))
do
if (( count % 2 == 0 ))
then
echo "Even number: $count"
else
echo "Odd number: $count"
fi
if (( count == 5 ))
then
echo "Reached 5! Continuing to next iteration..."
(( count++ ))
continue
fi
if (( count == 8 ))
then
echo "Reached 8! Exiting the loop..."
break
fi
(( count++ ))
done
echo "Loop finished!"
2. Save the script and change the permissions to make it executable.
3. Run the script:
The until
loop iterates numbers from 1 to 10, and for each iteration, it checks if the number is even or odd and prints the appropriate message. When the count reaches 5, it continues to the next iteration without executing the rest of the loop body.
When the count reaches 8, the loop exits using the break
statement. Finally, the script prints "Loop finished!" and terminates.
Conclusion
Effectively utilizing the until
loop in Bash can significantly increase your productivity and scripting skills. The loop allows you to automate tasks in a straightforward way, especially when you need to keep performing an action until a specific condition is met.
For more Bash tutorials, see how to append to a file in Bash or learn to use single and double quotes in Bash properly.