until - Linux
Overview
The until
command in Linux is used for executing a block of commands repeatedly until a certain condition is met. It is the opposite of the while
loop, which runs as long as the given condition is true. until
is most effective in scenarios where you need to wait for a specific condition to become true to proceed further in the script.
Syntax
The basic syntax for the until
command is:
until [ CONDITION ]
do
COMMANDS
done
- CONDITION: A test condition that is typically an exit status returned from a command.
until
loop continues to execute as long as this CONDITION evaluates to false (non-zero exit status). - COMMANDS: Commands that are executed each time the loop iterates and the condition is checked again afterward.
Options/Flags
until
uses conditions and commands within its structure, but it does not have specific flags or options itself. All complexities and variations come from the commands used as CONDITIONS and within the do-done block.
Examples
Basic Example
This script will keep printing the current time every second until the minute is equal to 30.
until [ $(date +%M) -eq 30 ]
do
echo "Current time: $(date)"
sleep 1
done
Intermediate Usage
This example checks for the existence of a file and proceeds once the file is not found:
until [ ! -f /tmp/myfile.txt ]
do
echo "Waiting for the file to be deleted..."
sleep 5
done
Common Issues
Infinite Loops
If the condition never evaluates to true, until
can result in an infinite loop. To avoid this:
- Ensure the condition can feasibly return true.
- Include a timeout mechanism or a maximum number of iterations.
Command Exit Status
Ensure that the commands used in CONDITION properly return non-zero exit statuses when expected. Using commands that do not handle exit statuses correctly can cause unexpected behavior.
Integration
until
can be combined with other Linux commands to perform more complex tasks. For example, checking the reachability of a server:
until ping -c 1 example.com > /dev/null
do
echo "Waiting for server to become reachable..."
sleep 5
done
echo "Server is up!"
Another integration can be with curl
for checking HTTP availability:
until curl --output /dev/null --silent --head --fail http://example.com
do
echo "Waiting for the website to be up..."
sleep 10
done
echo "Website is available now!"
Related Commands
while
: Executes a block of commands as long as the given condition is true.for
: Loops over a series of values.bash
: The shell within whichuntil
is typically used.
For more information and resources, you can refer to the man pages (man bash
) or online documentation about bash scripting.