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 Command Do If True done
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.
#!/bin/bashcounter=0while5 ]do COUNTER=$ ( Expr 1 ) echo $COUNTER Done
Run script, Output:
2 3 4 5
The while loop can be used to read keyboard information. In the following example, the input information is set to the variable film, press <Ctrl-D> to end the loop
#!/bin/bashecho'type <CTRL-D> to terminate'echo' ' while read FILM do echo ' yeah! Great file The $FILE" Done
Operation Result:
Type <CTRL-D> to terminateenter your most liked film:sound of Musicyeah! Great film The Sound of Music
Shell while loop