我正在尝试将来自 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 中,消息“检测到非零退出代码!” 不见了。知道为什么吗?谢谢!