在bash中使用tee时如何返回错误代码

问题描述 投票:0回答:1

我想使用

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

如果

Example 2
有任何错误,我想将“
return 1
”改为
first command
。 可以吗?如果可以怎么办?

linux bash ubuntu pipe tee
1个回答
0
投票

尝试

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

© www.soinside.com 2019 - 2024. All rights reserved.