2

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

3 Answers 3

8

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
Sign up to request clarification or add additional context in comments.

5 Comments

I couldn't find the -e option in gnu bash manual. You don't happen to have a link to a reference where I can read/learn about it?
@Qsp It's in the bash manual, "buried" deep among the options. Run this in your bash shell to see the relevant paragraphs: man bash|col -b|grep -A3 'OPTIONS'; man bash|col -b|grep -A 2 -- '-e *Exit'
@holygeek what's means of "--" in command "man bash|col -b|grep -A 2 -- '-e *Exit'"
@Leon -- tells grep that everything that comes after it are not to be treated as command line switches anymore. They are arguments. Without it grep would treat that '-e *Exit' as another switch. The use of -- is supported by programs that use the getopt library for processing command line switches and arguments.
I assume the -ex is the same as set -e; set-x which is documented here: gnu.org/software/bash/manual/…
0

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?

Comments

-2

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

1 Comment

At the prompt, exclamations are problematic even in single quotes, but in a script file, they're not. At the prompt, the exclamation mark is used by the csh-like history substitution mechanism (die, csh! die, history substitution mechanism from csh!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.