Skip to content

Exploring the Until Loop in Bash

Dive deep into the world of Bash scripting by mastering the until loop, a powerful tool for efficient iteration. This guide provides you with real-world examples and use cases, ranging from basic loop structures to more complex conditions, tailored to enhance script control and automation. Discover how to leverage the until loop to execute commands until a specified condition is met, making your Bash scripts more effective and streamlined.


Until Loop

i=1
until ((i > 10)); do
    # Loop body
    echo $i
    ((i++))
done

Until Sample

COUNTER=20
until [  $COUNTER -lt 10 ]; do
    echo COUNTER $COUNTER
    let COUNTER-=1
done

Until Loop with Command Output

until grep -q "pattern" file.txt; do
    # Loop body
    echo "Pattern not found, retrying..."
    sleep 1
done

Until Loop with Function

function check_service_running() {
    # Function to check if a service is running
    ps aux | grep "service_name" | grep -q -v grep
}

until check_service_running; do
    # Loop body
    echo "Service not running, waiting..."
    sleep 5
done

Until Loop with Multiple Conditions

i=0
retries=3
until ((i >= retries)) || command_to_execute; do
    # Loop body
    echo "Executing command, attempt $((i+1))..."
    ((i++))
    sleep 2
done