Bash Until Loop



Bash Until Loop

In Bash scripting, the until loop allows you to repeatedly execute a block of commands as long as a specified condition is false. It is the opposite of the while loop.


Syntax

until [ condition ]; do
    # commands
done

The basic syntax involves using until followed by a condition in square brackets, the commands to execute while the condition is false, and the loop ends with done.


Example Bash Until Loops

Let's look at some examples of how to use until loops in Bash:

1. Until Loop to Print Numbers

This script uses an until loop to print numbers from 1 to 5.

#!/bin/bash

count=1

until [ $count -gt 5 ]; do
    echo "Count: $count"
    ((count++))
done

In this script, the variable count is initialized to 1. The until loop checks if count is greater than 5 using the -gt operator. As long as count is less than or equal to 5, it prints the value of count and increments count by 1.

Until loop to print numbers in Bash

2. Until Loop to Check User Input

This script uses an until loop to repeatedly ask the user for input until they type 'exit'.

#!/bin/bash

input=""

until [ "$input" == "exit" ]; do
    read -p "Enter something (type 'exit' to quit): " input
    echo "You entered: $input"
done

In this script, the variable input is initialized to an empty string. The until loop checks if input is equal to 'exit' using the == operator. As long as input is not 'exit', it prompts the user to enter something and prints the entered value. The loop continues until the user types 'exit'.

Until loop to check user input in Bash

3. Until Loop to Wait for a File

This script uses an until loop to repeatedly check if a file exists and prints a message once the file is found.

#!/bin/bash

filename="example.txt"

until [ -f "$filename" ]; do
    echo "Waiting for $filename to be created..."
    sleep 2
done

echo "$filename found."

In this script, the variable filename is assigned the name of the file to check. The until loop checks if the file exists using the -f operator. As long as the file does not exist, it prints a message and waits for 2 seconds before checking again. Once the file is found, it prints a message indicating that the file has been found.

Until loop to wait for a file in Bash

Conclusion

The Bash until loop is a crucial tool for tasks that need to run until a condition becomes true in shell scripting. Understanding how to use until loops can help you automate and simplify many tasks in your scripts.