如果较早的部分出现故障,是否可以停止管道的较晚部分运行? [英] Can I stop later parts of a pipeline from running if an earlier part failed?

查看:58
本文介绍了如果较早的部分出现故障,是否可以停止管道的较晚部分运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个管道命令,例如:

I have a piped command such as:

set -euxo pipefail

echo 'hello' | foo | touch example.sh

这是输出:

$ set -euxo pipefail
$ echo hello
$ foo
$ touch example.sh
pipefail.sh: line 4: foo: command not found

我认为 set -e 会导致脚本退出.但是,即使无法识别 foo ,该脚本仍在执行 touch 命令.如果 foo 失败,如何退出?

I thought set -e would cause the script to exit however. But even though foo is unrecognized, the script is still executing the touch command. How do I get it to exit if foo fails?

推荐答案

除非数据从一端移动到另一端,否则您真的无法想到具有较早"或较晚"部分的管道.:管道的所有部分都同时运行.

You can't really think of a pipeline of having "earlier" or "later" parts, except insofar as data moves through them from one end to the other: All parts of a pipeline run at the same time.

因此,如果较早的部分出现故障,您将无法阻止后续的部分开始运行,因为因为较早的部分是在较早的部分发生故障的同时启动的.

Consequently, you can't prevent later parts from starting if an earlier part failed, because the later part started at the same time the earlier part did.

上面说的是,有 种机制可以使管道在发生故障时尽早关闭-这些机制的工作方式相同,而无需设置任何非默认的shell标志完全没有:

The above being said, there are mechanisms to allow a pipeline to shut down early in the event of a failure -- mechanisms which work the same way without needing to set any non-default shell flags at all:

  • 如果您使用的是设计用于管道右侧的工具(与 touch 不同),它将从stdin读取-因此会看到早期的EOF如果它左侧的组件出现故障.
  • 如果您使用的是专为在管道左侧使用的工具,则如果尝试编写的是右侧的东西,它将在尝试写入时收到 SIGPIPE 不再运行.
  • If you're using a tool designed to be used on the right-hand side of a pipeline (unlike touch), it will be reading from stdin -- and will thus see an early EOF should the components to the left of it fail.
  • If you're using a tool designed to be used on the left-hand side of a pipeline, it will receive a SIGPIPE when it attempts to write if the thing to the right of it is no longer running.

当然,如果从不写到stdout的程序或不从stdin读取的程序中进行管道传输,这些机制将不起作用-但这样的程序没有多大意义可以在管道中使用.

Of course, these mechanisms don't work if you're piping from a program that doesn't write to stdout, or into a program that doesn't read from stdin -- but such programs don't make much sense to use in pipelines anyhow.

这篇关于如果较早的部分出现故障,是否可以停止管道的较晚部分运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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