且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

一篇博客分清shell中的状态返回值-return-break-continue-exit

更新时间:2022-09-26 18:46:37

一篇博客分清shell中的状态返回值-return-break-continue-exit

 

一、breakcontinueexitreturn的区别和对比

 

条件与循环控制及程序返回值命令知识表

命令

说明

break n

如果省略n,则表示跳出整个循环n表示跳出循环的层数

continue n

如果省略n,则表示跳出本次循环,忽略本次循环剩余代码,进入循环的下一次循环。n表示退到第n层继续循环

exit n

表示退出当前shell程序n为上一次程序执行的状态返回值,n也可以省略,在下一个shell里可以通过“$?”接收exit nn值。

return n

用于在函数里作为函数的返回值,以判断函数执行是否正确,在下一个shell里可通过“$?”接收exit nn

 

 

 

二、breakcontinueexit功能执行流程图

 

1、在循环中break功能的执行流程逻辑图


一篇博客分清shell中的状态返回值-return-break-continue-exit

一篇博客分清shell中的状态返回值-return-break-continue-exit


 

 

 

 

2、在循环中bcontinue功能的执行流程逻辑图




一篇博客分清shell中的状态返回值-return-break-continue-exit

 一篇博客分清shell中的状态返回值-return-break-continue-exit



3、在循环中exit功能的执行流程逻辑图

一篇博客分清shell中的状态返回值-return-break-continue-exit

一篇博客分清shell中的状态返回值-return-break-continue-exit


 

三、用一个小脚本区分breakcontinueexitreturn

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
[root@xuegod63 ~]# vim 3.sh 
#!/bin/bash
#
#User : Mobanche
#Date : 2017-8-1
#Description :This shell script is used primarily to identify the state 
#             return value of a loop control that is distinguished from 
#             the return-break-continue-exit
  
if [ $# -ne 1 ]
then
        echo "usage: {conntiue|break|exit|return}"      
        exit 1
fi
  
test () {
        for ((i=1;i<=5;i++))
        do
                if [ $i -eq 3 ]
                then
                        $*
                fi
                echo $i
        done
        echo "I am function"
}
test $*
func_ret=$?
if [ `echo $*|grep return|wc -l` -eq 1 ]
then
        echo "return's exit status :$func_ret"
fi
echo OK


 

 

测试:

一篇博客分清shell中的状态返回值-return-break-continue-exit 










本文转自 于学康 51CTO博客,原文链接:http://blog.51cto.com/blxueyuan/1952770,如需转载请自行联系原作者