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 Commanddo Statement (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=0
- While [ $COUNTER -lt 5 ]
- Do
- COUNTER=' expr $COUNTER +1 '
- echo $COUNTER
- Done
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>.
Copy Plain Text New window
- echo ' type <CTRL-D> to terminate '
- echo- n ' Enter your most liked film: '
- While read FILM
- Do
- echo "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 Scripting Learning 19 shell while loop