While Loops and Until Loops

The commands in a while loop continue to execute as long as the condition is true. The general format of a while loop is:

while [ condition ]
do
      commands
done

The while loop first tests the condition. If it's true, the commands are executed. When the script reaches done, it returns to the while line and tests the condition again. If the condition's still true, it executes the commands again. If the condition is not true, it proceeds to the command following the while loop.

The simple shell script below executes the while loop four times:

#!/bin/bash
# Script name: numbers - outputs a list of numbers
n=0
while [ $n -lt 3 ]
do
      echo $n
      let n=n+1
done
echo After loop

The program execution is shown below:

					./numbers ...

Get Spring Into Linux® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.