Leon
Leon

Reputation: 2896

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

Upvotes: 2

Views: 551

Answers (3)

Yends
Yends

Reputation: 111

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

Upvotes: -2

holygeek
holygeek

Reputation: 16185

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

Upvotes: 8

Bruno Flávio
Bruno Flávio

Reputation: 778

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?

Upvotes: 0

Related Questions