bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

errexit is not respected on nested functions when parent function precee


From: cirrus . mazurka-0t
Subject: errexit is not respected on nested functions when parent function preceeds ||
Date: Wed, 9 Aug 2023 00:04:15 +0800

I think I've found a bug with Bash's handling of errexit.



The following code:

``` bash
#!/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:

``` bash
#!/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 cause each called function to exit on initial failure:

``` bash
#!/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



Cross-posted to https://stackoverflow.com/q/76861137/130638



Bash verison:

```
GNU bash, version 5.2.15(1)-release (aarch64-apple-darwin22.1.0)
Copyright (C) 2022 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
```


reply via email to

[Prev in Thread] Current Thread [Next in Thread]