break n层循环的理解

在学习Shell脚本的break与continue语句时,有一些困惑,就是break n可以跳出几层循环的问题,continue也是如此。不过弄懂了break n的问题,continue n的问题应该也清楚了。

第一步:break 1

新建一个loop.sh脚本,输入以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/bin/bash
for ((m=1;m<=2;m++))
do
for((j=1;j<=3;j++))
do
for ((i=1;i<=4;i++))
do
if [ $i -eq 3 ]
then
break 1
fi
echo "The m cycle is $m the out cycle is $j,and inner cycle is $i"
done
done
done

运行结果,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
biotest@ubuntu:~/loop$ bash loop.sh
The m cycle is 1 the out cycle is 1,and inner cycle is 1
The m cycle is 1 the out cycle is 1,and inner cycle is 2
The m cycle is 1 the out cycle is 2,and inner cycle is 1
The m cycle is 1 the out cycle is 2,and inner cycle is 2
The m cycle is 1 the out cycle is 3,and inner cycle is 1
The m cycle is 1 the out cycle is 3,and inner cycle is 2
The m cycle is 2 the out cycle is 1,and inner cycle is 1
The m cycle is 2 the out cycle is 1,and inner cycle is 2
The m cycle is 2 the out cycle is 2,and inner cycle is 1
The m cycle is 2 the out cycle is 2,and inner cycle is 2
The m cycle is 2 the out cycle is 3,and inner cycle is 1
The m cycle is 2 the out cycle is 3,and inner cycle is 2

第二步:break 2

现在将break 1改为break 2,运行,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/bin/bash
for ((m=1;m<=2;m++))
do
for((j=1;j<=3;j++))
do
for ((i=1;i<=4;i++))
do
if [ $i -eq 3 ]
then
break 2
fi
echo "The m cycle is $m the out cycle is $j,and inner cycle is $i"
done
done
done

运行:

1
2
3
4
5
biotest@ubuntu:~/loop$ bash loop.sh
The m cycle is 1 the out cycle is 1,and inner cycle is 1
The m cycle is 1 the out cycle is 1,and inner cycle is 2
The m cycle is 2 the out cycle is 1,and inner cycle is 1
The m cycle is 2 the out cycle is 1,and inner cycle is 2

第三步,break 3

现在将break 2改为break 3,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/bin/bash
for ((m=1;m<=2;m++))
do
for((j=1;j<=3;j++))
do
for ((i=1;i<=4;i++))
do
if [ $i -eq 3 ]
then
break 3
fi
echo "The m cycle is $m the out cycle is $j,and inner cycle is $i"
done
done
done

运行,如下所示:

1
2
3
biotest@ubuntu:~/loop$ bash loop.sh
The m cycle is 1 the out cycle is 1,and inner cycle is 1
The m cycle is 1 the out cycle is 1,and inner cycle is 2

从上面的结果可以看出来:①最内层的是第1层循环,再次是第2层循环,最外层就是第3层循环。