🎓 A1Learner
🔍
0 of 47 lessons completed

Bash While Loops

A while loop repeats a block of commands while a test stays true. The test is checked before every round of the loop.

Count up with while

The counter starts at one and grows by one each round. The loop stops after printing three.

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

Count down with while

This counter starts at three and falls by one each round. The loop stops when the count reaches zero.

count=3
while [ $count -ge 1 ]
do
  echo "Count is $count"
  count=$((count - 1))
done

Grow a value until the test fails

The number doubles on every round. The loop stops once the doubled value is no longer less than twenty.

n=1
while [ $n -lt 20 ]
do
  echo "$n"
  n=$((n * 2))
done

Example

count=5
while [ $count -ge 1 ]
do
  echo "Tick $count"
  count=$((count - 1))
done
echo "Time is up"

Key points

  • A while loop checks its test before each round.
  • The loop stops as soon as the test becomes false.
  • A counter variable often controls how long the loop runs.
  • The update line changes the counter inside the loop.
  • Without an update, the test may never become false.
  • While loops suit jobs where the number of rounds is not known in advance.

In this example, the counter starts at five and drops by one on each round. The while test stays true while the counter is at least one. The last echo prints after the loop ends.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What happens if a while loop never changes the variable in its test?