bash set-e(errexit)只适用于管道中的最后一个命令



我一直在阅读关于bashset -e选项的文章,但仍然有点困惑,为什么在文件test-output.xml不存在的情况下,下面的管道会继续执行。

设置set -e是否仅适用于最后一个命令的退出状态?我在该选项的文档中找不到该语句(例如,tldp.org->bash选项(。

谢谢你的帮助!

#!/usr/local/bin/bash
set -e
fail_tests=`cat test-output.xml|grep '^<testng-results '|perl -e 'print "0";'`
echo $?
echo "fail_tests: [$fail_tests]"

输出:

cat: test-output.xml: No such file or directory
0
fail_tests: [0]

但是,如果我将命令更改为:

#!/usr/local/bin/bash
set -e
fail_tests=`cat test-output.xml|grep '^<testng-results '|perl -e 'print "0"; exit 1;'`
echo $?
echo "fail_tests: [$fail_tests]"

它输出:

cat: test-output.xml: No such file or directory

使用bash版本运行:

➜  ~ /usr/local/bin/bash -version
GNU bash, version 5.0.18(1)-release (x86_64-apple-darwin19.5.0)
Copyright (C) 2019 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

实际上,管道的退出代码是管道中最后一个命令的退出代码。因此,默认情况下,set -e仅适用于每个管道中的最后一个命令。

Bash使用set -o pipefail来扩展行为,或者使用set -e来扩展管道中的任何命令。

相关内容

最新更新