可以控制循环内部的两条命令:break命令 continue命令
break命令
break命令是在处理过程中跳出循环的一种简单方法。可以使用break命令跳出任何类型的循环,包括while循环和until循环
#跳出单循环 #!/bin/bash #breaking out of a for loop for var1 in 1 2 3 4 5 do if [ $var1 -eq 3 ] then break fi echo "Iteration number:$var1" done echo "The for loop in completed" 当var1=3时,跳出循环! [root@localhost ~]# ./test17.sh Iteration number:1 Iteration number:2 The for loop in completed
#跳出内循环 #!/bin/bash #breaking out of an inner loop for (( a = 1; a < 4; a++ )) do echo "out side loop:$a" for (( b = 1; b < 100; b++ )) do if [ $b -eq 5 ] then break fi echo "In loop:$b" done done
[root@localhost ~]# ./test19.sh out side loop:1 In loop:1 In loop:2 In loop:3 In loop:4 out side loop:2 In loop:1 In loop:2 In loop:3 In loop:4 out side loop:3 In loop:1 In loop:2 In loop:3 In loop:4
#跳出外循环:break n n表明要跳出的循环级别,默认n=1,代表跳出当前循环!若n=2,将停止外循环 #!/bin/bash #breaking out of an outer loo for (( a = 1; a < 4; a++ )) do echo "Out Loop:$a" for (( b = 1; b <100; b++ )) do if [ $b -gt 4 ] then break 2 fi echo "Inner loop:$b" done done [root@localhost ~]# ./test20.sh Out Loop:1 Inner loop:1 Inner loop:2 Inner loop:3 Inner loop:4
continue命令 continue是一种提前停止循环内命令,而不完全终止循环方法! #!/bin/bash #using the continue command for (( var1 = 1; var1 < 13; var1++ )) do if [ $var1 -gt 3 ] && [ $var1 -lt 10 ] then continue fi echo "Iteration Number:$var1" done
[root@localhost ~]# ./test21.sh Iteration Number:1 Iteration Number:2 Iteration Number:3 Iteration Number:10 Iteration Number:11 Iteration Number:12 if-then语句条件(值大于5小于10)满足时,shell执行continue命令,跳过该循环中剩下的命令,但是循环继续进行!如果if-the语句条件不满足时,那么循环恢复正常! 与break命令一样,continue命令也可以指定循环级别: continue n #!/bin/bash #testing an outer loop for (( a = 1; a <= 3; a++ )) do echo "Iteration $a" for (( b = 1; b < 4; b++ )) do if [ $a -gt 2 ] && [ $a -lt 4 ] then continue 2 fi var3=$[ $a * $b ] echo "The result of $a * $b is $var3" done done
[root@localhost ~]# ./test22.sh Iteration 1 The result of 1 * 1 is 1 The result of 1 * 2 is 2 The result of 1 * 3 is 3 Iteration 2 The result of 2 * 1 is 2 The result of 2 * 2 is 4 The result of 2 * 3 is 6 Iteration 3
重定向循环的输出: #!/bin/bash for (( a = 1; a < 10; a++ )) do echo "The number is $a" done > test23.txt echo "The command is finished" [root@localhost ~]# ./test23.sh The command is finished [root@localhost ~]# cat test23.txt The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9