英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论