此问题已在此处有答案:
Pipe output and capture exit status in Bash(16个回答)
2个月前关闭。
我想使用tee
将any 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
。是否可能,如果是,该怎么办?
1条答案
按热度按时间llew8vvj1#
尝试
set -o pipefail
,这将传播非零出口到后面的管道成员