Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"source script" does not honor "#!/bin/bash -ex" and exit when a command fails

Tags:

bash

shell

I get confused after google search "set -e" in bash. Based on my understanding, with "set -e" the bash will exit whenever there is an error. But if you run two simple scripts below in mac such as source myscript, you can still see "can not get here"...Any idea?

#!/bin/bash -ex 
fun_with_error_code() {
  return 1;
}
fun_with_error_code
echo "can not get here"

Another one

#!/bin/bash -ex
commandNotExit
echo "can not get here"

My rookie mistake. Charles Duffy's answer below solves the problem. These two scripts work fine, it is just because "source myscript" doesn't honor shebang line.

like image 364
batilei Avatar asked Oct 18 '25 17:10

batilei


1 Answers

The shebang line is used to let a script tell the operating system what interpreter to run it with.

When you use source, you're telling your current shell interpreter to evaluate the script's commands internally.

Thus, the operating system doesn't need to start a new interpreter for the script.

Thus, the operating system never invokes the shebang line.

Thus, arguments such as -ex on that line are never invoked when your script is run with source.


Solutions are twofold:

  • Use set -e as a separate line if you really do want to have this effect (but see BashFAQ #105 for reasons why you shouldn't).
  • Don't use source except when you have a very explicit reason to run a script within your existing interpreter (and change that interpreter's state). And when you do have such a reason, running set -e is almost certainly a thing you don't want to do.
like image 69
Charles Duffy Avatar answered Oct 21 '25 08:10

Charles Duffy