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 $aNum in
- 1| 2| 3| 4| 5) echo "Your number is $aNum!"
- ;;
- *) echo "You don't select a number between 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
- For var1 in 1 2 3
- Do
- For var2 in 0 5
- Do
- if [ $var 1 -eq 2-a $var 2 -eq 0 ] /c0>
- Then
- break 2
- Else
- Echo "$var 1 $var 2"
- fi
- Done
- Done
As above, break 2 means to jump out of the outer loop directly. Operation Result:
1 01 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 $aNum in
- 1| 2| 3| 4| 5) echo "Your number is $aNum!"
- ;;
- *) echo "You don't select a number between 1 to 5!"
- Continue
- Echo "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/bash
- NUMS="1 2 3 4 5 6 7"
- For NUM in $NUMS
- Do
- Q= ' expr $NUM % 2 '
- if [ $Q -eq 0 ]
- Then
- echo "Number is an even number!!"
- Continue
- fi
- echo "Found odd number"
- Done
Operation Result:
Found Odd Numbernumber is an even number!! Found Odd Numbernumber is an even number!! Found Odd Numbernumber is an even number!! Found Odd number
Shell break and Continue commands