Home > database >  How to have bash inherit failures from stdin subshells
How to have bash inherit failures from stdin subshells

Time:04-29

Given the following contrived code:

#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit

echo 'before'

mapfile -t tuples < <(exit 1)
# ^ what option do I need to enable so the error exit code from this is not ignored

echo 'after'

Which produces:

before
after

Is there a set or shopt option that can be turned on such that <(exit 1) will cause the caller to inherit the failure, and thus preventing after from being executed? Such as what inherit_errexit and pipefail do in other contexts.

CodePudding user response:

In bash 4.4 or later, process substitutions will set $!, which means you can wait on that process to get its exit status.

#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit

echo 'before'

mapfile -t tuples < <(exit 1)
wait $!

echo 'after'

mapfile itself (in general) won't have a non-zero status, because it's perfectly happy read what, if anything, the process substitution produces.

CodePudding user response:

You can assign a variable with the output of the command. The variable assignment propagates errors from the command substitution.

t=$(exit 1)
echo 'after'
mapfile -t tuples <<<"$t"
  • Related