Difference between "while" and "until" in Bash

Kyrol picture Kyrol · Nov 27, 2011 · Viewed 43.1k times · Source

What is the real difference between while and until ?

I'd like to know if it's possible to do an increasingly loop with "until" and a descending loop with while.

Because I saw that if I do this

COUNTER=0
     while [ $COUNTER -lt 10 ]; do
         echo The counter is $COUNTER
         let COUNTER+=1 
     done

and this

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

they work well.

But if I do the opposite, for example:

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

the script doesn't end.

Does this means that we cannot do a reverse loop with a while in bash?

Answer

Oliver Charlesworth picture Oliver Charlesworth · Nov 27, 2011

while runs the loop while the condition is true. until runs the loop until the condition is true (i.e. while the condition is false).

See http://www.gnu.org/software/bash/manual/bashref.html#Looping-Constructs.