shell 的控制结构 (break 和 continue语句)
break 语句可以结束while,for,until或select等结构的执行,即从结构中跳出。退出循环后,转到done语句后继续执行。
[root@sziit~]# vim breaks.sh (示例)
#!/bin/bash
#filename:breaks
echo "enter the number:"
read N
for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
do
if [ $i -eq $N ] ;then
echo "-------exit for loop-----"
break
else
echo "------current is $i loop----"
fi
done
[root@sziit ~]# ./breaks.sh (测试结果)
enter the number:
5
------current is 1 loop----
------current is 2 loop----
------current is 3 loop----
------current is 4 loop----
-------exit for loop-----
continue 语句用来跳过本次循环中的代码,直接跳回到循环的开始位置。如果条件为真则开始下一次循环,否则退出循环。
[root@sziit ~]# vim continues.sh (示例)
#!/bin/bash
#filename:continues
echo "output the number:"
read N
echo "------------------"
int=1
for int in `seq 7`
do
if [ $N -gt 7 ] ;then
echo "please enter a number[1-7]"
break
elif [ $N -le 0 ];then
echo "please enter a number[1-7]"
break
else
if [ $int -eq $N ] ;then
echo "-"
continue
fi
fi
echo "$int"
done
[root@sziit ~]# ./continues.sh (测试结果)
output the number:
4
------------------
1
2
3
-
5
6
7