Shell Learning 20 - Shell Out of the Loop

In the process of looping, sometimes it is necessary to force to break out of the loop when the end condition of the loop is not reached. Like most programming languages, Shell also uses break and continue to break out of the loop.
break command
The break command allows to break out of all loops (terminate execution of all subsequent loops).
In the example below, the script goes into an infinite loop until the user enters a number greater than 5. To break 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 do not 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, indicating the number of layers to jump out of the loop. E.g:
break n
Indicates to jump out of the nth level loop.
Here is an example of a nested loop that breaks out of the loop if var1 equals 2 and var2 equals 0:
#!/bin/bash
for var1 in 1 2 3
do
for var2 in 0 5
do
if [ $var1 -eq 2 -a $var2 -eq 0 ]
then
break 2
else
echo "$var1 $var2"
be
done
done
As above, break 2 means to jump out of the outer loop directly. operation result:
1 0
1 5
continue command
The continue command is similar to the break command, with only one difference, it will not jump out of all loops, only the current loop.
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 do not select a number between 1 to 5!"
continue
echo "Game is over!"
;;
esac
done
Running the code finds that when a number greater than 5 is entered, the loop in this example does not end, the statement
echo "Game is over!"
will never be executed.
Similarly, continue can also be followed by a number to indicate which layers of loops to jump out of.
Look at another example of continue:
#!/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
be
echo "Found odd number"
done
operation result:
Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325684540&siteId=291194637