During the loop, there are times when you need to force out of the loop without reaching the end of the loop, and the shell uses two commands to implement the function: Break and continue.
Break command
The break command allows you to jump out of all loops (terminating all loops after execution).
In the following example, the script goes into a dead loop until the user enters a number greater than 5. To jump out of this loop, return to the shell prompt with the break command.
Copy Code code as follows:
#!/bin/bash
While:
Todo
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
Continue
The continue command is similar to the break command, except that it does not jump out of all loops and simply jumps out of the current loop.
Modify the example above to:
Copy Code code as follows:
#!/bin/bash
While:
Todo
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 found that when you enter a number greater than 5, the loop in the example does not end, and the statement
Copy Code code as follows:
Will never be executed.