inherit_errexit

nicolaw 25th April 2018 at 8:30am
Bash

You might expect the following to stop on error due to it's use of set -eE (see docs), but it does not:

set -eEu
a=$(false; echo "FUUUUUU")
echo $a
FUUUUUU

-E If set, any trap on ERR is inherited by shell functions, command substitutions, and commands executed in a subshell environment. The ERR trap is normally not inherited in such cases.

However the following works as intended by stopping on error:

a=$(set -e; false; echo "FUUUUUU")

There is a inherit_errexit shopt flag to make subprocesses inherit the errexit flag, but it is Bash 4.4+ only.

If set, command substitution inherits the value of the errexit option, instead of unsetting it in the subshell environment. This option is enabled when POSIX mode is enabled.

You may be bitten with x=$(complex_function) where some statement in the middle of the complex_function is failing.

Thanks to @node13h for bringing this little tid-bit to my attention!