Shell Script · Until Loop

Shell Scripting · Lesson 12

Until Loop

Understand until loop behavior in shell scripting. Difference between while and until. Retry mechanism using until. Production use cases.

What is an Until Loop?

An until loop runs a block of code repeatedly until a given condition becomes true.

Why Use an Until Loop?

Reverse Logic

Useful when condition should become true to stop.

Polling Tasks

Wait for a process, file, or service to appear.

Automation

Automate wait-based operations.

Until Loop Syntax

until syntax
syntax
until [ condition ]
do
commands
done

Until Loop Examples

1. Basic Until Loop

The loop runs until the condition becomes true.

terminal — bash
until-loop
count=1
 
until [ $count -gt 5 ]
do
echo "Count: $count"
count=$((count + 1))
done

2. Until Loop with User Input

Loop runs until the user types 'exit'.

terminal — bash
until-loop
input=""
 
until [ "$input" = "exit" ]
do
read -p "Type 'exit' to quit: " input
done

3. Until File Exists

Script waits until a file becomes available.

terminal — bash
until-loop
until [ -f /tmp/data.txt ]
do
echo "Waiting for file..."
sleep 2
done
 
echo "File found!"

4. Service Check Example

Wait until a service starts running.

terminal — bash
until-loop
until systemctl is-active --quiet sshd
do
echo "Waiting for SSH service..."
sleep 3
done
 
echo "SSH service is running"

Best Practices

Recommended Practices

  • Avoid infinite loops by updating condition properly.
  • Use sleep to reduce CPU usage.
  • Use clear exit conditions.
  • Log or echo progress for clarity.

Practice Task – Until Loop

  • Write a script that waits until a file exists.
  • Repeat a task until user enters "stop".
  • Use until loop with numeric condition.

Next lesson: Case Statement