有沒有一種方法可以將一個程式的輸出傳送到另外兩個程式?

有沒有一種方法可以將一個程式的輸出傳送到另外兩個程式?

抱歉,如果這是一個愚蠢的問題,但我正在嘗試完成類似的事情,但一行:

$ prog1 | prog2
$ prog1 | prog3

所以,我基本上想執行 prog1 並將輸出分別透過管道傳輸到 prog2 和 prog3 (不是鍊式管道)。起初,我嘗試使用 tee 但這似乎不對,因為它將輸出轉儲到文件中(這不是我想要的)。

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

在某些時候,我可能想將其擴展到將輸出傳輸到兩個以上的程序,但我現在只是開始簡單。

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

答案1

工藝替代。

... | tee >(prog2) | ...

答案2

與 Ignacio 的答案類似,您可以使用臨時命名管道mkfifo(1)

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

它有點冗長,但它可以在沒有進程替換的系統上工作,例如dash.這sleep 1是為了處理任何競爭條件。

答案3

有一個小實用程序聚四氟乙烯它的作用是:

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

而不是寫入文件,聚四氟乙烯寫入命令列上給出的所有 fd。

聚四氟乙烯是其一部分管道執行器

答案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

相關內容