有没有一种方法可以将一个程序的输出传递给另外两个程序?


28

抱歉,如果这是一个愚蠢的问题,但是我想在一行上完成这样的事情:

$ prog1 | prog2
$ prog1 | prog3

因此,我基本上想执行prog1并将输出分别管道传输到prog2和prog3(而不是链式管道)。最初,我尝试使用tee,但这似乎并不正确,因为它会将输出转储到文件中(这不是我想要的)。

$ prog1 | tee prog2 | prog3 # doesn't work - creates file "prog2"

在某个时候,我可能想将其扩展到将输出传递给两个以上的程序,但是我现在只是从简单开始。

$ prog1 | prog2
$ prog1 | prog3
$ prog1 | prog4
...

我认为zsh可以做到这一点。
基思2012年

Answers:



16

与Ignacio的答案类似,您可以使用使用的临时命名管道mkfifo(1)

mkfifo /tmp/teedoff.$$; cmd | tee /tmp/teedoff.$$ | prog2 & sleep 1; prog3 < /tmp/teedoff.$$; rm /tmp/teedoff.$$

它有点冗长,但是可以在没有进程替代的系统上运行,例如dash。该sleep 1是处理任何竞争条件。


6

有一个小型公用程序ptee可以完成此工作:

prog1 | ptee 2 3 4 2> >(prog2) 3> >(prog3) 4> >(prog4)

ptee不会写入文件,而是写入命令行上给出的所有fds。

聚四氟乙烯是部分pipexec


4

您不需要任何bashisms或特殊文件,也不需要任何文件-无论如何在Linux中都不是:

% { prog1 | tee /dev/fd/3 | prog2 >&2 ; } 3>&1 | prog3 

{ { printf %s\\t%s\\t%s\\n \
    "this uneven argument list" \
    "will wrap around" to \
    "different combinations" \
    "for each line." "Ill pick out" \
    "a few words" "and grep for them from" \
    "the same stream." | 
 tee /dev/fd/3 /dev/fd/4 | 
 grep combination >&2 ; } 3>&1 |
 grep pick >&2 ; } 4>&1 | 
 grep line

different combinations  for each *line.*  Ill pick out
different combinations  for each line.  Ill *pick* out
different *combinations*  for each line.  Ill pick out

我为grep突出显示的结果加注了星标,以表明它们不仅是来自同一流的三个结果,而且还是单独的grep流程匹配的结果。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.