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.
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:
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).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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With