Loops and Iterations

Here is an example of a loop that will repeat some action until a condition is met:

number=0
while [ $number -lt 10 ]; do
    echo "Number = $number"
    number=$((number + 1))
done
echo "Finished!"

This produces:

Number = 0
Number = 1
Number = 2
Number = 3
Number = 4
Number = 5
Number = 6
Number = 7
Number = 8
Number = 9
Finished!

We assigned the value 0 to the variable number. The while command expects a test, in this case whether $number is less than 10.

The semicolon again breaks the line, and the do command repeats everything up to the done command until the while condition is no longer true.

Inside the do loop, we repeat, or iterate, two lines. The first echoes the number, and the second adds one to it. When $number reaches 10, it is no longer less than 10, the condition is false, and the do loop quits. The program goes on to the next line.

Printed from linux.bz (Shell Script Loops - Linux.bz, Linux in Belize)