A while loop is used to continuously execute a series of commands and also to read data from an input file; commands are usually test conditions. Its format is:
The following is a basic while loop, the test condition is: if COUNTER is less than 5, then return true. COUNTER starts at 0 and increases by 1 each time the loop is processed. Running the above script returns the numbers 1 to 5, then terminates.
while command do Statement(s) to be executed if command is true doneAfter the command is executed, control returns to the top of the loop, starting from the beginning until the test condition is false.
The following is a basic while loop, the test condition is: if COUNTER is less than 5, then return true. COUNTER starts at 0 and increases by 1 each time the loop is processed. Running the above script returns the numbers 1 to 5, then terminates.
COUNTER=0 while [ $COUNTER -lt 5 ] do COUNTER='expr $COUNTER+1' echo $COUNTER doneRunning the script, output:
1 2 3 4 5while loop can be used to read keyboard information. In the following example, the input information is set to the variable FILM, and pressing <Ctrl-D> ends the loop.
echo 'type <CTRL-D> to terminate' echo -n 'enter your most liked film: ' while read FILM do echo "Yeah! great film the $FILM" doneRunning the script produces output similar to the following:
type <CTRL-D> to terminate enter your most liked film: Sound of Music Yeah! great film the Sound of Music