proper way to detect shell exit code when errexit option set

后端 未结 14 1510
甜味超标
甜味超标 2021-01-30 12:52

I prefer to write solid shell code, so the errexit & nounset is alway set.

The following code will stop at bad_command line

#!/bin/b         


        
14条回答
  •  离开以前
    2021-01-30 13:44

    In case you want to detect the exit code of a compound list (or a function), and have errexit and nounset applied there, you can use this kind of code:

    #!/bin/sh
    set -eu
    unset -v unbound_variable
    
    f() {
        echo "before false"
        false
        echo "after false"
    }
    
    g() {
        echo "before unbound"
        var=$unbound_variable
        echo "after unbound"
    }
    
    set +e
    (set -e; f)
    echo error code of f = $?
    set -e
    
    echo still in main program
    
    set +e
    (set -e; g)
    echo error code of g = $?
    set -e
    
    echo still in main program
    

    The above should print non-zero error codes for both functions f and g. I suppose this works by any POSIX shell. You can also detect the error code in EXIT trap, but the shell exits thereafter. The problem with other proposed methods is that the errexit setting is ignored when an exit status of such a compound list is tested. Here is a quote from the POSIX standard:

    The -e setting shall be ignored when executing the compound list following the while, until, if, or elif reserved word, a pipeline beginning with the ! reserved word, or any command of an AND-OR list other than the last.

    Note that if you have defined your function like

    f() (
        set -e
        ...
    )
    

    it is enough to do

    set +e
    f
    echo exit code of f = $?
    set -e
    

    to get the exit code.

提交回复
热议问题