如何让bash从stdin子shell继承失败



给定以下人为代码:

#!/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'

生产:

before
after

是否有一个set或shopt选项可以打开,使<(exit 1)将导致调用者继承失败,从而阻止after被执行?例如inherit_errexitpipefail在其他情况下的作用。

bash4.4或更高版本中,进程替换将设置$!,这意味着您可以等待该进程获得其退出状态。

#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit
echo 'before'
mapfile -t tuples < <(exit 1)
wait $!
echo 'after'

mapfile本身(通常)不会有非零状态,因为它非常乐意读取进程替换产生的内容。

可以在命令的输出中指定一个变量。变量赋值从命令替换传播错误。

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

如果您有Bash 4.2或更高版本,因为您已经设置了errexitpipefail,您可以通过使用:

来避免这个问题
...
shopt -s lastpipe
exit 1 | mapfile -t tuples

shopt -s lastpipe使管道中的最后一个命令在当前shell中运行。查看shopt -s lastpipe如何影响bash脚本行为?在这种情况下,这意味着mapfile读取的tuples值可以在稍后的代码中访问。

最新更新