The following code:
#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s huponexit
shopt -s inherit_errexit
function child_function {
return 1
}
function parent_function {
child_function
echo "parent noticed child exit code as $?"
}
function grandparent_function {
local ec
ec=0 && parent_function || ec="$?"
echo "grandparent noticed parent exit code as $ec"
}
grandparent_function
Will surprisingly output:
parent noticed child exit code as 1
grandparent noticed parent exit code as 0
Changing the code to:
#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s huponexit
shopt -s inherit_errexit
function child_function {
return 1
}
function parent_function {
child_function || return "$?"
echo "parent noticed child exit code as $?"
}
function grandparent_function {
local ec
ec=0 && parent_function || ec="$?"
echo "grandparent noticed parent exit code as $ec"
}
grandparent_function
Returns the expected result of:
grandparent noticed parent exit code as 1
Is there an additional setting that I need to set to fix this? Or is this a bug in bash?
The reason I believe it is a bug, is that changing the code to not use the || ec="$?"
will respect the -e/errexit
option (Exit immediately if a command exits with a non-zero status) and have each failed function exit immediately:
#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s huponexit
shopt -s inherit_errexit
function child_function {
return 1
}
function parent_function {
child_function
echo "parent noticed child exit code as $?"
}
function grandparent_function {
parent_function
echo "grandparent noticed parent exit code as $?"
}
grandparent_function
Outputs nothing and returns exit code 1