通知左侧失败的管道右侧? [英] Inform right-hand side of pipeline of left-side failure?

查看:130
本文介绍了通知左侧失败的管道右侧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经越来越喜欢在我的shell脚本中使用函数之间的发电机状花纹。事情是这样的:

I've grown fond of using a generator-like pattern between functions in my shell scripts. Something like this:

parse_commands /da/cmd/file | process_commands

然而,这种模式的基本问题是,如果parse_command遇到一个错误,我发现通知process_command的唯一途径,它未能通过明确告诉它(例如回声FILE_NOT_FOUND)。这意味着,在每parse_command潜在断层操作将不得不围栏。

However, the basic problem with this pattern is that if parse_command encounters an error, the only way I have found to notify process_command that it failed is by explicitly telling it (e.g. echo "FILE_NOT_FOUND"). This means that every potentially faulting operation in parse_command would have to be fenced.

有没有办法process_command没有可以检测到左侧退出以非零退出code?

Is there no way process_command can detect that the left side exited with a non-zero exit code?

推荐答案

请问管道进程继续下去,即使第一个进程已经结束,或者是你有没有知道的第一个过程失败的方法的问题?

Does the pipe process continue even if the first process has ended, or is the issue that you have no way of knowing that the first process failed?

如果是后者,你可以看看 PIPESTATUS 变量(这实际上是一个BASH阵列)。这会给你的第一个命令的退出code:

If it's the latter, you can look at the PIPESTATUS variable (which is actually a BASH array). That will give you the exit code of the first command:

parse_commands /da/cmd/file | process_commands
temp=("${PIPESTATUS[@]}")
if [ ${temp[0]} -ne 0 ]
then
    echo 'parse_commands failed'
elif [ ${temp[1]} -ne 0 ]
then
    echo 'parse_commands worked, but process_commands failed'
fi

否则,你将不得不使用协同进程。

Otherwise, you'll have to use co-processes.

这篇关于通知左侧失败的管道右侧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆