While Loops and Until Loops

team bbl


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 0 1 2 After loop 

The until loop is very similar, except it stops looping when the condition is true. To get the above output, you would use the following until loop, changing -lt to -eq:

 n=0 until [ $n -eq 3 ] do       echo $n       let n=n+1 done echo After loop 

    team bbl



    Spring Into Linux
    Spring Into Linux
    ISBN: 0131853546
    EAN: 2147483647
    Year: 2005
    Pages: 362
    Authors: Janet Valade

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net