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

我试图将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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值