What does set -e mean in a bash script?

后端 未结 8 893
醉酒成梦
醉酒成梦 2020-11-22 15:46

I\'m studying the content of this preinst file that the script executes before that package is unpacked from its Debian archive (.deb) file.

The scr

8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 16:23

    As per bash - The Set Builtin manual, if -e/errexit is set, the shell exits immediately if a pipeline consisting of a single simple command, a list or a compound command returns a non-zero status.

    By default, the exit status of a pipeline is the exit status of the last command in the pipeline, unless the pipefail option is enabled (it's disabled by default).

    If so, the pipeline's return status of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully.

    If you'd like to execute something on exit, try defining trap, for example:

    trap onexit EXIT
    

    where onexit is your function to do something on exit, like below which is printing the simple stack trace:

    onexit(){ while caller $((n++)); do :; done; }
    

    There is similar option -E/errtrace which would trap on ERR instead, e.g.:

    trap onerr ERR
    

    Examples

    Zero status example:

    $ true; echo $?
    0
    

    Non-zero status example:

    $ false; echo $?
    1
    

    Negating status examples:

    $ ! false; echo $?
    0
    $ false || true; echo $?
    0
    

    Test with pipefail being disabled:

    $ bash -c 'set +o pipefail -e; true | true | true; echo success'; echo $?
    success
    0
    $ bash -c 'set +o pipefail -e; false | false | true; echo success'; echo $?
    success
    0
    $ bash -c 'set +o pipefail -e; true | true | false; echo success'; echo $?
    1
    

    Test with pipefail being enabled:

    $ bash -c 'set -o pipefail -e; true | false | true; echo success'; echo $?
    1
    

提交回复
热议问题