It seems that the set -e option in Bash gets reset inside of functions, when those functions are invoked via a $(...) expansion.
This surprises me, and I'm not sure if it is a bug or not. I have not been able to find a description of this behavior in the (usually quite thorough) Bash manpage.
Note: here are some other similar SO posts:
But neither of them deals with $(...), which is not really discussed in the manpage either.
I also cannot find reference to this issue in the excellent Bash FAQ 105.
Here is a small program to demonstrate the issue:
echo "Initial: $-"
set -eu
echo "After set: $-"
function foo() {
echo "Inside foo: $-"
}
foo
function bar() {
false # I'd expect this to immediately fail
echo "Inside bar: $-"
}
# When a $(...) construct is involved, 'bar' runs to completion!
x=$(bar)
echo "We should never get here ... but we do."
echo "$x"
For me, on Bash version 5.0.11(0)-release, I get the following output:
Initial: hB
After set: ehuB
Inside foo: ehuB
We should never get here ... but we do.
Inside bar: huB
So, as you can see, the -u option does get "passed through" to the function in all cases. And the -e option gets passed through when the function is called normally. But only in the special case of $(bar) does the -e option get reset.
Does anyone know if this is documented behavior, or otherwise explainable?
It makes no sense to me (:
$(…)notation is Command Substitution and is described in the Bash manual. It doesn't detail the interaction withset -e, though.just shell functions- command substitution creates a child process. Och, there isinherit_errexitshopt$$inside a shell function. It is the same number both inside and out.$BASHPID. Forecho $BASHPID; $(echo $BASHPID >&2)I see a different number. Still if you really want to, just read the docs on command substitutionexecuting command in a subshell environment