1.return用法解释
linux shell中return用来返回函数的返回值
样例:
[root@kibana ~]# cat return.sh
#!/bin/bashnum=$#function return_test()
{if [ $num == 0 ];thenreturn 22fi
}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/bashfor outerloop in 1 2 3 4 5
doecho -n "Group $outerloop: "for innerloop in 1 2 3 4 5doecho -n "$innerloop "if [ "$innerloop" -eq 3 ];thenbreak#当innerloop值等于3时,退出innerloop的for循环,即innerloop循环的值4和5不会打印出来,但是outerloop的for循环不受影响fi doneecho
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/bashfor outerloop in 1 2 3 4 5
doecho -n "Group $outerloop: "for innerloop in 1 2 3 4 5doecho -n "$innerloop "if [ "$innerloop" -eq 3 ];thenbreak 2#当innerloop值等于3时,退出innerloop及outerloop的for循环,即innerloop循环的值4和5不会打印出来,outerloop 2、3、4、5循环不会再进行fi doneecho
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/bashLIMIT=19echo
echo "Printing Numbers from 1 to 20 (4 and 9 not included)."a=0
while [ $a -le "$LIMIT" ]
doa=$(($a+1))if [ "$a" -eq 4 ] || [ "$a" -eq 9 ]then#除了4和9continue#跳过本次循环剩余的语句fiecho -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/bashfor outer in I II III IV V
doecho; echo -n "Group $outer: "for inner in 1 2 3 4 5 6 7 8 9 10doif [ "$inner" -eq 8 ]thencontinue 2#在第2层循环上的continue,也就是“外部循环”.fiecho -n "$inner "#8 9 10将不会被echo.done
done
echo;echoexit 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/bashfor ((i=1;i<5;i++))
doif [ $i -eq 3 ]thenexitfiecho $i
done
[root@kibana ~]# sh exit.sh
1
2
[root@kibana ~]# echo $?
0
[root@kibana ~]#