ubuntu bash中使用tee时如何返回错误码[duplicate]

guykilcj  于 8个月前  发布在  其他
关注(0)|答案(1)|浏览(98)

此问题已在此处有答案

Pipe output and capture exit status in Bash(16个回答)
2个月前关闭。
我想使用teeany command (first command)的输出写入文件,但我想从first command而不是tee命令中获取返回代码。

实施例1:下面的代码将返回1,这是预期的:

cp -unknown-args "hello"
echo "return code is $?"

---output---
cp: invalid option -- 'k'
Try 'cp --help' for more information.
return code is 1

实施例2:以下代码将返回0,这是意外的:

cp -unknown-args "hello" | tee test.txt
echo "return code is $?"

---output---
cp: invalid option -- 'k'
Try 'cp --help' for more information.
return code is 0

如果first command有任何错误,我想将“Example 2“改为return 1。是否可能,如果是,该怎么办?

llew8vvj

llew8vvj1#

尝试set -o pipefail,这将传播非零出口到后面的管道成员

相关问题