Bourne/bash shell script: while loop syntax

Contributor Icon Contributed by Rex  
Tag Icon Tagged: Bourne shell scripting  

A while loop allows execution of a code block an arbitrary number of times until a condition is met. This recipe describes the while loop syntax for the various Bourne shells (sh, ksh, bash, zsh, etc.) and provides examples.


General syntax:

while [ condition ]
do
code block;
done

Any valid conditional expression will work in the while loop. The following code asks the user for input and verifies the input asking for a y or n and will repeat the process until a y answer is received.

verify="n"
while [ "$verify" != y ]
do
echo "Enter option: "
read option
echo "You entered $option. Is this correct? (y/n)"
read verify
done

Another useful while loop is a simple one, and infinite loop. If the conditional is “1″ the loop will run until something else breaks it (such as the break keyword):

while [ 1 ]
do
ps -ef | grep [s]endmail | wc -l
sleep 5
done

This while loop will display the number of sendmail processes running every five seconds until the loop or executing shell is killed. The brackets in [s]endmail are a regular expression trick that prevents the ‘grep [s]endmail’ process from being counted.

 

8 Comments -


  1. Sharad said on February 13, 2009

    Helpfull for me…

    Thanks
    Sharad

  2. temporaldoom said on August 19, 2010

    I think it’s worthwhile to note (at least for me) that whitespace matters… esp. for C/C++/Java people who are used to “while(){}” syntax where you can have any number of whitespace around the operators…

    while[ ] will NOT work but
    while [ ] will work…

  3. Duncan Anderson said on December 14, 2010

    Another variation on the infinite loop is:

    while true
    do
    …….
    done

  4. Fengyang Leng said on March 13, 2011

    helpful for me. Thank you

  5. Coder-X said on April 29, 2011

    did a lot of help !! :)

  6. anjali said on August 26, 2011

    This made me understand that spaces are more important
    thanks a lot

  7. sarath antony said on September 13, 2011

    #a substitute for the “true” is “:” (column)

    while :
    do
    ……………
    done #is also a forever loop

  8. ramu r said on January 5, 2012

    very helpful info, thanks

 

RSS feed for comments on this post. TrackBack URL

Leave a comment -