我试图将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.
标签:bash,linux,pipe,bash-trap,tee
来源: https://codeday.me/bug/20190624/1276221.html