开发者

why return statement in function will cause the bash script end

when I run the follow bash script, it will never print "bye!". It seems that return statement in dummy function will cause the bash script end, leave the left script not excute.

#!/bin/bash -开发者_运维问答ex

dummy () {
    if [ $1 -eq 0 ] ; then 
        return 0
    else
        return 55
    fi  
}

dummy 0
echo "when input 0, dummy will return $?"

dummy 50
echo "when input 50, dummy will return $?"

echo "bye!"

output:

+ dummy 0
+ '[' 0 -eq 0 ']'
+ return 0
+ echo 'when input 0, dummy will return 0'
when input 0, dummy will return 0
+ dummy 50
+ '[' 50 -eq 0 ']'
+ return 55


Your she-bang line: #!/bin/bash -ex

That -e option tells bash to exit immediately after a command returns a non-zero value.

In this case it's the [ $1 -eq 0 ] when $1 is 55 so your script exits immediately.

Try run you script like this:

$ bash yourscript.sh

vs.:

$ bash -e yourscript.sh


change

#!/bin/bash -ex

to:

#!/bin/bash

and it will work.

Actually you can do it with #!/bin/bash -x also.

You meant to accomplish something else with the -e option?


Use single quotes around 'bye!'. With double quotes the "!" causes a problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜