In the loop, sometimes you need to force out of the loop when the loop end condition is not reached, like most programming languages, the shell also uses break and continue to jump out of the loop.
Break command
The break command allows you to jump out of all loops (all loops after the execution is terminated).
In the following example, the script enters a dead loop until the user enters a number greater than 5. To jump out of this loop and return to the shell prompt, use the break command.
#!/bin/Bash while : Do Echo-N"Input A number between 1 to 5:"Read Anum Case$aNuminch 1|2|3|4|5)Echo "Your number is $aNum!" ;; *)Echo "You does not select a number betewwn 1 to 5,game is over!"Break ; ;; Esac Done~ ~
In a nested loop, the break command can also be followed by an integer that indicates a loop that jumps out of the first layer. For example:
Break n
Indicates a jump out of the nth layer loop.
Here is an example of a nested loop, if Var1 equals 2, and var2 equals 0, jump out of the loop:
#!/bin/Bash forVar1inch 1 2 3 Do forVar2inch 0 5 Do if[$var 1-eq2-A $var 2-eq0 ] Then Break1 Else Echo "$var 1 $var 2" fi Done Done~
Operation Result:
1 0 1 5 3 0 3 5
Continue command
The continue command is similar to the break command, with only a little difference, and it does not jump out of all loops and just jumps out of the current loop.
To modify the above example:
#!/bin/Bash while : Do Echo-N"Input A number between 1 to 5"Read Anum Case$aNuminch 1|2|3|4|5)Echo "Your number is $aNum!" ;; *)Echo "You does not select a number between 1 to 5!"ContinueEcho "Game is over!" ;; Esac Done
Running code discovery, when you enter a number greater than 5, the loop in this example does not end, and the statement
Echo " Game is over! "
Will never be executed.
Similarly, the continue can be followed by a number, indicating that the first layer jumps out of the loop.
Let's look at a continue example:
#!/bin/bashnums="1 2 3 4 5 6 7" forNuminch$NUMS DoQ=$(Expr$NUM%2) if[$Q-eq0 ] Then Echo "Number is an even number!!"Continuefi Echo "Found Odd number" Done
Operation Result:
Found Odd Numbernumberis an even number!! Found Odd Numbernumberis an even number!! Found Odd Numbernumberis an even number!! Found Odd number
Shell break and Continue commands