The while loop is used to continuously execute a series of commands and to read data from the input file; the command is usually a test condition. The format is:
While Commanddostatement (s) to being executed if command is Truedone
The command finishes, control returns to the top of the loop, and starts from the beginning until the test condition is false.
The following is a basic while loop, and the test condition is: Returns True if counter is less than 5. Counter starting from 0, counter plus 1 for each cycle of processing. Run the above script, return the number 1 to 5, and then terminate.
Counter=0while [$COUNTER-lt 5]docounter= ' expr $COUNTER +1 ' echo $COUNTERdone
Run script, Output:
12345
The while loop can be used to read keyboard information. In the following example, the input information is set to the variable film, ending the loop by <Ctrl-D>.
echo ' type <CTRL-D> to terminate ' echo-n ' Enter your most liked film: ' while read Filmdoecho ' yeah! Great film The $FILM "done
Run the script with the output similar to the following:
Type <CTRL-D> to terminateenter your most liked film:sound of musicyeah! Great film The Sound of Music
Shell Learning 18-shell While loop