1.return用法解释
linux shell中return用来返回函数的返回值
样例:
[root@kibana ~]# cat return.sh
#!/bin/bash
num=$#
function return_test()
{
if [ $num == 0 ];then
return 22
fi
}
return_test
echo $?
[root@kibana ~]# sh return.sh
22
[root@kibana ~]# sh return.sh 11
0
[root@kibana ~]#
2.break用法解释
break n:表示退出n层循环;如果省略n,则表示只能退出最内层的循环
样例(break-1 level):
[root@kibana ~]# cat break-1.sh
#!/bin/bash
for outerloop in 1 2 3 4 5
do
echo -n "Group $outerloop: "
for innerloop in 1 2 3 4 5
do
echo -n "$innerloop "
if [ "$innerloop" -eq 3 ];then
break
#当innerloop值等于3时,退出innerloop的for循环,即innerloop循环的值4和5不会打印出来,但是outerloop的for循环不受影响
fi
done
echo
done
[root@kibana ~]# sh break-1.sh
Group 1: 1 2 3
Group 2: 1 2 3
Group 3: 1 2 3
Group 4: 1 2 3
Group 5: 1 2 3
[root@kibana ~]#
样例(break-2 level):
[root@kibana ~]# cat break-2.sh
#!/bin/bash
for outerloop in 1 2 3 4 5
do
echo -n "Group $outerloop: "
for innerloop in 1 2 3 4 5
do
echo -n "$innerloop "
if [ "$innerloop" -eq 3 ];then
break 2
#当innerloop值等于3时,退出innerloop及outerloop的for循环,即innerloop循环的值4和5不会打印出来,outerloop 2、3、4、5循环不会再进行
fi
done
echo
done
echo
[root@kibana ~]# sh break-2.sh
Group 1: 1 2 3
[root@kibana ~]#
3.continue用法解释
continue n:n表示把n层循环的剩余代码都去掉,但是循环的次数不变;如果省略n,表示只会去掉本次循环的剩余代码,即跳过本次循环,进入循环的下一次迭代,循环的次数也是不变
样例(continue-1 level):
[root@kibana ~]# cat continue-1.sh
#!/bin/bash
LIMIT=19
echo
echo "Printing Numbers from 1 to 20 (4 and 9 not included)."
a=0
while [ $a -le "$LIMIT" ]
do
a=$(($a+1))
if [ "$a" -eq 4 ] || [ "$a" -eq 9 ]
then
#除了4和9
continue
#跳过本次循环剩余的语句
fi
echo -n "$a "
#在$a等于4和9的时候,这句将不会执行
done
echo;echo
echo Printing Numbers from 1 to 20,but something happens after 3.
[root@kibana ~]# sh continue-1.sh
Printing Numbers from 1 to 20 (4 and 9 not included).
1 2 3 5 6 7 8 10 11 12 13 14 15 16 17 18 19 20
Printing Numbers from 1 to 20,but something happens after 3.
[root@kibana ~]#
样例(continue-2 level):
[root@kibana ~]# cat continue-2.sh
#!/bin/bash
for outer in I II III IV V
do
echo; echo -n "Group $outer: "
for inner in 1 2 3 4 5 6 7 8 9 10
do
if [ "$inner" -eq 8 ]
then
continue 2
#在第2层循环上的continue,也就是“外部循环”.
fi
echo -n "$inner "
#8 9 10将不会被echo.
done
done
echo;echo
exit 0
[root@kibana ~]# sh continue-2.sh
Group I: 1 2 3 4 5 6 7
Group II: 1 2 3 4 5 6 7
Group III: 1 2 3 4 5 6 7
Group IV: 1 2 3 4 5 6 7
Group V: 1 2 3 4 5 6 7
[root@kibana ~]#
4.exit用法解释
exit n:n表示返回n,n为正整数(n>=0),一般情况下,n=0表示正常退出shell程序,n>1表示退出shell程序异常;n也可以忽略,当shell正常退出时,返回0;当shell异常退出时,返回1。
样例:
[root@kibana ~]# cat exit.sh
#!/bin/bash
for ((i=1;i<5;i++))
do
if [ $i -eq 3 ]
then
exit
fi
echo $i
done
[root@kibana ~]# sh exit.sh
1
2
[root@kibana ~]# echo $?
0
[root@kibana ~]#