gpt4 book ai didi

linux - Bash:使用管道运算符时陷阱 ERR 不起作用

转载 作者:IT王子 更新时间:2023-10-29 01:21:58 26 4
gpt4 key购买 nike

我正在尝试将来自 stdout 和 stderr 的所有内容记录到一个日志文件中,同时仍然保留控制台。为此,我只是将:|& tee -a log_file.log 添加到每个命令。
但是,如果脚本期间发生任何错误,我也想运行自定义命令。为此,我在脚本的开头添加了以下内容:trap "echo Non-zero exit code detected"ERR
问题是通过使用管道运算符,陷阱中的回显不再执行。

脚本 1,没有管道:

$cat test.sh
#!/bin/bash

trap "echo Non-zero exit code detected!" ERR

function fail_please()
{
echo "Returning non-zero exit code!"
return 1
}

fail_please

输出 1:

$ ./test.sh 
Returning non-zero exit code!
Non-zero exit code detected!

脚本 2,带管道:

$ cat test.sh
#!/bin/bash

trap "echo Non-zero exit code detected!" ERR

function fail_please()
{
echo "Returning non-zero exit code!"
return 1
}

fail_please |& tee log_file.log

输出 2:

$ ./test.sh
Returning non-zero exit code!
$ cat log_file.log
Returning non-zero exit code!

在输出 2 中,消息“检测到非零退出代码!”不见了。知道为什么吗?谢谢!

最佳答案

ERR 陷阱针对“简单命令”触发,管道不是简单命令。

它可能会触发整个管道的结果(我不确定),您可以通过设置 pipefail 来获得更接近您想要的结果。

(注意:这是人们通常不推荐使用 set -e 的原因之一,因为它有像这样令人惊讶的细节。)

pipefail 起作用的原因是,通常管道的返回状态是最后一个命令的返回,但是如果有 pipefail,它就会成为最后一个命令的返回状态那失败了。

The return status of a pipeline is the exit status of the last command, unless the pipefail option is enabled. If pipefail is enabled, the pipeline’s return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit success- fully.

关于linux - Bash:使用管道运算符时陷阱 ERR 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27546819/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com