Until Loop in Bash

Bash scripting provides a set of tools for automating tasks and streamlining workflows, with loops being a key feature to execute specific tasks repetitively in a controlled manner. Among various loop types such as for, while, do-while, and until, the until loop stands out for its concise approach. In this article, I will explore the bash until loop giving you some demonstration of different types of it and a few practical examples of this.

What is Until Loop in Bash?

The until loop in bash is a control statement that possesses a block of code and a condition. It executes the block of code repeatedly as long as the condition remains unsatisfied. Whereas the while loop executes the code as long as the condition remains satisfied.

Syntax of Until Loop in Bash

The common syntax of a until loop in Bash script is:

until [conditions]
do
[commands]
done
EXPLANATION
  • At first, the [conditions] will be checked.
  • In case of condition is false, the loop will execute the [commands].
  • Then the condition will be checked again. If the condition is false, the commands will be executed again. The loop will terminate only if the condition becomes true.

5 Cases of Bash Until Loop

The bash until loop can be implemented using single or multiple conditions. The until loop can be finite or infinite. In this section, I will demonstrate some cases of it.

1. Simple Until Loop with Single Condition

The until loop does the task specified inside the do block as long as the condition inside the condition block is true. Each execution of the do block is known as iteration.

Here is a bash script of a simple until loop:

#!/bin/bash

counter=1
until [ $counter -gt 5 ]
do
echo Counter: $counter
((counter++))
done
EXPLANATION

The until [ $counter -gt 5 ] command will check the condition of the loop where the -gt option will check whether the value of the counter variable is greater than 5. If the condition returns false, the echo Counter: $counter command will print the value of the counter variable and the ((counter++)) command will increase the value of the counter variable by one. Then the condition will be checked again and execution of the codes will continue repetitively until the value of the counter becomes 5, which will make the condition true.

A simple until loop containg bash script.The above image shows that the bash until loop has printed the numbers from 1 to 5 on the terminal.

2. Array Iteration Using Until Loop

Array Iteration means going through each array element one by one. The iteration task is done using loops. For this, define an array like array_name = {item1, item2, item3, .. item4}. Then, iterate through the array using a loop.

Here is a bash script to iterate through each element of an array using the until loop:

#!/bin/bash

# Define an array
colors=("red" "green" "blue")
# Get the length of the array
array_length=${#colors[@]}
# Initialize an index
index=0
# Use an until loop to iterate through the array
until [ $index -ge $array_length ]; do
echo "Element at index $index: ${colors[$index]}"
((index++))
done
EXPLANATION

Here, the array_length=${#colors[@]} command finds the length of the colors array and keeps it to the array_length variable.  Then the $index -ge $array_length  will compare whether the index is equal to or greater than the array_lengh with the help of the -ge option. If the condition returns false, the echo "Element at index $index: ${colors[$index]}" command will print the first element of the colors array and the ((index++)) command will increase the value of the index by one.  After that, the condition will be checked again and execution of the codes will continue repetitively until the index value becomes equal to the array_length which will make the condition true.

Each element of the colors array has been printed on the terminal.The image shows that the until loop has iterated through each element of the colors array.

3. Until Loop with “break” and “continue” Statement

The break command exits the current loop and passes the control to the following statement, and the continue command skips the current iteration and jumps to the next iteration of the loop. Incorporating these two commands programmers can skip a certain iteration on a until loop, or break the until loop and accomplish the desired task.

Here I have tried a bash script incorporating both the break and the continue commands:

#!/bin/bash

counter=0
until false
do
((counter++))
if [[ $counter -eq 6 ]]
then
  continue
elif [[ $counter -ge 10 ]]
  then
  break
fi
echo "Counter = $counter"
done
EXPLANATION

Here, in the until false command, you can see the condition of the until loop is false. That means the until loop will not terminate unless the break command interrupts. After that, the if [[ $counter -eq 6 ]] command checks if the value of the counter variable is equal to 6. If so, the continue command will be executed which will skip the current iteration and jump to the next iteration.

Afterward, the elif [[ $counter -ge 10 ]] command checks if the value of the counter variable is equal to or greater than 10. If so, the break command will be executed which will break the until loop. Unless the above-mentioned two cases, each value of the counter variable will be printed on the terminal.

The break and the continue statements have been used.The image shows that the until loop has printed 1 to 9 and skipped 6 using the break command and the continue command.

4. Infinite Loop Using Until

The until loop ends when the condition within the until loop is satisfied. If the condition inside the until loop is constant “false”, and nothing makes the condition true, the until loop becomes an infinite loop. In such cases, the loop does a certain task for infinite times.

Here is a sample bash script on an infinite loop using until:

#!/bin/bash

until false
do
echo "Infinite loop. Press CTRL+C to exit!"
sleep 1
done
EXPLANATION

The until false command marks the condition of the until loop as “false”. Which will not be changed over time. Hence, the loop becomes infinite. Therefore, the echo command will be executed again and again for an infinite time.

Execution of an infitine loop.The above image shows that the until loop has executed an infinite loop which has been interrupted by pressing CTRL+C.

5. Until Loop with Multiple Conditions

The condition block within the until loop can contain multiple conditions. These conditions can exist in the condition block of the until loop with the help of logical and (&&) or logical or(||) operators. In the case of the logical or operator(||), if all of the conditions are false then the loop will execute the commands. And, in the case of the logical and operator(&&) if any of the conditions are false then the loop will execute the commands. This facilitates programmers to set the conditions of the until loop depending on multiple criteria.

Here is a bash script of the until loop containing multiple conditions in the condition statement:

#!/bin/bash

n=1
sum=0
until [[ $n -gt 10  || $sum -gt 18 ]]
do
sum=$(($sum + $n))
echo "n = $n & Summation of first n = $sum"
((n++))
done
EXPLANATION

The $n -gt 10  || $sum -gt 18 command checks whether the value of variable n is greater than 10 or the value of the sum is greater than 18. If any of the conditions become true, it exits the until loop. Here, the sum=$(($sum + $n)) command has added the sum with the n variable. Finally, the ((n++)) command has increased the value of n by one.

Multiple conditions have been used on the until loop.The image shows that the until loop has printed the iteration value and summation result depending on the two conditions of the until loop.

5 Practical Examples of Bash Until Loop

The bash until loop can be used to solve various kinds of real-life problems. Here are some of the practical examples of using the until loop in bash:

1. Automating File Existence Checks in Bash

The bash until loop gives programmers a means to check the existence of a file. It is a convenient feature to search for an important file in a server that might contain thousands of files. An easy approach is to keep the file-checking command on the condition block of the until loop. It will iterate the checking process again and again until the file is created by a user in the background and the file-checking command returns a zero status.

Here is the complete bash script to wait for a file to exist:

#!/bin/bash

file_path="/home/susmit/file.txt"
until [ -f $file_path ]
do
echo "Waiting for the file to be detected.."
sleep 1
done
echo "The file exists."
EXPLANATION

In the until [ -f $file_path ] command, the -f option will search for the existence of the file_path. As long as the file is not found in the designated directory, the checking process will continue.

The file.txt exits.The above image shows that the file.txt has been found.

2. Waiting for Valid Input from User

Input from a user can be used inside the condition of the until loop. To check the validity of the input from the user, compare the input from the user with your desired input. If the input is valid, the until loop will be terminated and the command after the loop will be executed. If the input is not as desired, the until loop will ask for input again and will not be terminated before getting a valid input.

Here’s how you can do it:

#!/bin/bash

input=""
until [ "$input" = "yes" ] || [ "$input" = "no" ]; do
read -p "Please enter 'yes' or 'no': " input
done
echo "Valid input received: $input"
EXPLANATION

The "$input" = "yes" ] || [ "$input" = "no"  command inside the until loop condition compares the input string with “yes” or “no”. If any one of the comparison results is true, it terminates the until loop and prints a line on the terminal.

Valid input from the user found.

3. Guess the Number Game

The until loop executes the specified command until the condition inside the until loop becomes true. A number-guessing game can easily be implemented by using the until loop where the main task will be to guess a number. The script will repeatedly ask you to guess the number until the guess is correct.

Here is the bash script of a number guessing game:

#!/bin/bash

original_number=29
your_guess=0
trial=1
until [ $your_guess -eq $original_number ]; do
read -p "Guess the secret number: " your_guess
((trial++))
if [ $your_guess -lt $original_number ]; then
echo "Too low!"
elif [ $your_guess -gt $original_number ]; then
echo "Too high!"
fi
done
echo "Congratulations! You guessed the secret number correctly in $trial trial."
EXPLANATION

The $your_guess -eq $original_number statement inside the until loop condition will compare if the your_guess is equal to the original_number variable. If the condition output is true, the subsequent commands will be executed. Here the read -p "Guess the secret number: " your_guesscommand will ask for input from the user and keep the user input into your_guess. Then the if [ $your_guess -lt $original_number ]; then command will check if your_guess is less than the original_number with the help of -lt option. If the condition result is true then the echo "Too low!" command will be executed. If the condition result is false then the elif [ $your_guess -gt $original_number ]; then command will compare whether your_guess is greater than original_number. If the condition result is true then the echo "Too high!" command will be executed. If the your_guess is neither less than nor greater than the original_number then these two must be equal thereby the echo “Congratulations! You guessed the secret number correctly in $trial trial.” command will print the ultimate result of the game the until loop will be terminated.

The original number is guessed in 3 trials.

4. Creating a Simple Timer

A timer or countdown timer counts a certain time. The until loop incorporated with the sleep command can develop a simple yet effective timer that counts a certain time. The sleep command defines the wait time during each iteration of the until loop and continues until the condition becomes true.

Here is a bash script of a simple timer:

#!/bin/bash

seconds=5
until [ $seconds -eq 0 ]; do
echo "Countdown: $seconds"
sleep 1
((seconds--))
done
echo "Time's up!"
EXPLANATION

The $seconds -eq 0 command inside the until loop condition will check whether the “seconds” is equal to “0”. Until the condition becomes true, the echo "Countdown: $seconds" command will be executed. And, the sleep 1 command will wait for 1 second before going to the next iteration. Finally, the ((seconds--)) command will decrease the value of the seconds variable by one.

The simple timer countdown.

5. Check Network Connectivity

The easy approach to checking network connectivity is to send a single Internet Control Message Protocol (ICMP) echo request to www.google.com and receive the consequent response. The until loop can be used to check the connectivity where the ping command will do the task of request sending and receiving the response as long as an appropriate response is not received.

Here is a bash script for checking network connectivity:

#!/bin/bash

#Until loop that continues until a successful ping to www.google.com
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."
EXPLANATION

The ping -c1 www.google.com command inside the until loop condition will send a single ICMP echo request to Google and wait for the response. The “&>/dev/null” part will redirect both standard output and standard error to “/dev/null” which suppresses the output of the ping command.

Afterward, the sleep 5 command will wait for 5 seconds before the next trial to send a request and receive the consequent response. The until loop will repeat as long as the ping command returns a non-zero status which means the ping command has not received any response against the sent request.

Internet connectivity found.

Conclusion

In conclusion, the bash until loop is a useful feature in Bash scripting for scenarios where programmers want to repeatedly execute a block of code until a specific condition becomes true. From basic syntax to practical examples, this article is your one-stop solution to learn the skill of looping in Bash. Do not forget to share your thoughts in the comment box!

People Also Ask

What is the difference between the while loop and the until loop in Linux?

The prime distinction between the while loop and the until loop is the condition block. The while loop runs as long as the condition is true. On the contrary, the until loop runs as long as the condition is false. The until loop terminates as soon as the condition becomes true.

What is the until loop condition in Bash?

The until loop condition in Bash is a control flow statement that permits the execution of code repeatedly until a specific condition is satisfied.

What are the three types of loops in Bash scripting?

There are three types of loops in Bash scripting. These are the for loop, the while loop, and the until loop.

What is the until operator in Bash?

The until operator is a part of the bash until loop. The until loop iterates through a block of commands as long as the condition is false.

How do I restart a loop in Bash?

The continue statement can restart a loop in Bash. It skips the current iteration and jumps into the next iteration without executing the subsequent codes of the loop.

Can you loop through an array in Bash?

Yes, you can loop through an array in Bash. Firstly, you have to define an array. Then access the array element one by one using your preferred types of loop.

Related Articles


<< Go Back to Loops in Bash | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Susmit Das Gupta

Hello everyone. I am Susmit Das Gupta, currently working as a Linux Content Developer Executive at SOFTEKO. I am a Mechanical Engineering graduate from Bangladesh University of Engineering and Technology. Besides my routine works, I find interest in going through new things, exploring new places, and capturing landscapes. Read Full Bio

Leave a Comment