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

huangapple go评论73阅读模式
英文:

How to return error code when using tee in bash

问题

我想使用 tee 命令将 任何命令(第一个命令) 的输出写入文件,但我想获取 第一个命令 而不是 tee 命令的返回码。

示例 1:以下代码将返回 1,这是预期的:

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

---输出---

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 $?"

---输出---

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

我想要让“示例 2”在第一个命令出现错误时返回 1。是否可能,如果是,如何实现?

英文:

I want to use tee to write the output of any command (first command) to a file, but I want to get the return code from the first command instead of the tee command.

Example 1: The following code will return 1 and it is expected:

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

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

Example 2: The following code will return 0 and it is unexpected:

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

I want to make "Example 2" to return 1 if the first command has any error.
Is it possible and how to do if yes?

答案1

得分: 1

尝试使用 set -o pipefail,这将将非零退出代码传递给后续的管道成员。

英文:

try set -o pipefail, this will propagate nonzero exits to later pipe members

huangapple
  • 本文由 发表于 2023年8月5日 10:58:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839982.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定