Bourne/bash shell script: while loop syntax

Contributor Icon Contributed by Rex Date Icon January 9, 2004  
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.

Previous recipe | Next recipe |
 
  • Sharad
    Helpfull for me...

    Thanks
    Sharad
blog comments powered by Disqus