1

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

9

1 Answer 1

1

Thanks to the commenters:

And these supporting resources:

I created this workaround for the question's code sample using the subshell technique:

#!/usr/bin/env bash

set -e

function child_function {
    return 1
}
function parent_function {
    child_function
    echo "parent noticed child exit code as $?"
}
function grandparent_function {
    local ec=0
    set +e; (set -e; parent_function); ec="$?"; set -e
    echo "grandparent noticed parent exit code as $ec"
}

grandparent_function

However, the subshell technique prevents side effects, as modifications do not escape the subshell.

I spent a few more days on this issue, and created a gist with various techniques, including one that works with side effects:

https://gist.github.com/balupton/21ded5cefc26dc20833e6ed606209e1b

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.