Quantcast
Channel: What does 'set -e' mean in a Bash script? - Stack Overflow
Viewing all articles
Browse latest Browse all 13

Answer by kenorb for What does 'set -e' mean in a Bash script?

$
0
0

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 $?success0$ bash -c 'set +o pipefail -e; false | false | true; echo success'; echo $?success0$ 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

Viewing all articles
Browse latest Browse all 13

Trending Articles