Search code examples
bashshellunixexit-code

combined use of bash options for error handling (e.g. pipefail, errexit, inherit_errexit)


Consider the following Bash script:

#!/usr/bin/env bash

set -o errexit pipefail
shopt -s inherit_errexit

( echo hello ; exit 1 ) | cat

echo world

Running with version 5.0.17, the output is as follows:

hello
world

However, the subshell responsible for printing hello would have failed, with a nonzero exit status. Part of a pipe, with enabling the optionpipefail, the entire pipe should similarly fail, with the same status (the subsequent item in the pipe of course returning a zero status by itself). Thus, the pipe should evaluate to a nonzero status, which due to errexit (if not inherit_errexit as well) would prompt the immediate termination of the script, without reaching the final statement printing world.

As seen, the prediction is not accurate that the final print statement is not reached.

Why?


Solution

  • You're only setting the errexit setting, not pipefail. You can't put multiple options after -o, you need to repeat the -o option. Everything else is being put into the positional arguments.

    So change

    set -o errexit pipefail
    

    to

    set -o errexit -o pipefail