管道中的条件步骤 [英] Conditional step in a pipeline

查看:65
本文介绍了管道中的条件步骤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给管道一个类似"A | B | C | D | E"的东西,我想把步骤C的条件作为步骤C的条件.

Given a pipeline something like "A|B|C|D|E", I want to make step C conditional on the result of step B. Something like this:

A | B | if [ $? -ne 0 ]; then C; else cat; fi | D | E

但这似乎行不通;无论B的结果如何,都永远不会执行C.我正在寻找更好的解决方案.

But this doesn't seem to work; C is never executed no matter what the result of B. I'm looking for a better solution.

我知道管道的每个步骤都在其自己的子外壳中运行.因此,我无法将环境变量传递回管道.但是此管道位于Gnu并行环境中,其中许多此类管道同时运行,而且它们都不知道任何唯一值(它们仅处理数据流,不需要知道源,父脚本处理必要的分隔).这意味着使用临时文件也不可行,因为没有任何方法可以使文件名唯一.甚至$$似乎都没有给我每个步骤都相同的值.

I understand that each step of a pipeline runs in its own subshell. So I can't pass an environment variable back to the pipeline. But this pipeline is in a Gnu Parallel environment where many such pipelines are running concurrently and none of them knows any unique value (they just process the data stream and don't need to know the source, the parent script handles the necessary separation). That means that using a temporary file isn't practical, either, since there isn't any way to make the file names unique. Even $$ doesn't seem to give me a value that is the same in each of the steps.

推荐答案

您不能使管道成为有条件的,因为命令是并行运行的.如果在退出 B 之前不运行 C B 的输出将通过管道输送到哪里?

You can't make a pipeline conditional because the commands are run in parallel. If C weren't run until B exited, where would B's output be piped to?

您需要将 B 的输出存储在变量或临时文件中.例如:

You'll need to store B's output in a variable or a temporary file. For instance:

out=$(mktemp)
trap 'rm "$out"' EXIT
if A | B > "$out"; then
    C < "$out"
else
    cat "$out"
fi | D | E

这篇关于管道中的条件步骤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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