Shell Learning 18 - Shell while loop

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:
while command
do
Statement(s) to be executed if command is true
done
After 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
done
Running the script, output:
1
2
3
4
5
while 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"
done
Running 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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325777561&siteId=291194637