Bourne/Bash Shell Script: While Loop Syntax

Posted January 9, 2004 by Rex in Bourne shell scripting

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


The general syntax is as follows:

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, an 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.

The Conversation

Follow the reactions below and share your own thoughts.