🎓 A1Learner
🔍
0 of 47 lessons completed

Bash Until Loops

An until loop repeats a block of commands until a test becomes true. It runs while the test is false, which is the opposite of a while loop.

Count up with until

The test asks if count is greater than three. The loop runs while the answer is no.

count=1
until [ $count -gt 3 ]
do
  echo "Count is $count"
  count=$((count + 1))
done

Count down with until

The loop runs until the counter reaches zero. Each round prints the counter and then lowers it by one.

count=3
until [ $count -eq 0 ]
do
  echo "Count is $count"
  count=$((count - 1))
done

Wait for a value to grow

The value doubles on each round. The loop stops when the value reaches twenty or more.

n=2
until [ $n -ge 20 ]
do
  echo "$n"
  n=$((n * 2))
done

Example

count=1
until [ $count -gt 4 ]
do
  echo "Round $count"
  count=$((count + 1))
done
echo "Four rounds done"

Key points

  • An until loop runs while its test is false.
  • The loop stops as soon as the test becomes true.
  • A while loop and an until loop can do the same job with opposite tests.
  • The counter still needs an update line inside the loop.
  • The test is checked before every round, just like with while.

In this example, the loop prints Round for counts one through four. The test becomes true when the count reaches five. The final echo then prints after the loop.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

When does an until loop stop?