如何使用 Unix(或 Windows)中的(最好是未命名的)管道将一个进程的标准输出发送到多个进程? [英] How can I send the stdout of one process to multiple processes using (preferably unnamed) pipes in Unix (or Windows)?
问题描述
我想将进程 proc1 的标准输出重定向到两个进程 proc2 和 proc3:
I'd like to redirect the stdout of process proc1 to two processes proc2 and proc3:
proc2 -> stdout
/
proc1
proc3 -> stdout
我试过了
proc1 | (proc2 & proc3)
但它似乎不起作用,即
echo 123 | (tr 1 a & tr 1 b)
写
b23
到标准输出而不是
a23
b23
推荐答案
编者注:
- >(…)
是一个 过程替换 这是一些 POSIX兼容shell的非标准shell特性:bash
、ksh
、zsh
.
- 这个答案意外地通过管道too发送了输出进程替换的输出:echo 123 |三通>(tr 1 a) |tr 1 b
.
- 进程替换的输出将不可预测地交错,并且,除了在 zsh
中,管道可能会在 >(…)
中的命令执行之前终止.
Editor's note:
- >(…)
is a process substitution that is a nonstandard shell feature of some POSIX-compatible shells: bash
, ksh
, zsh
.
- This answer accidentally sends the output process substitution's output through the pipeline too: echo 123 | tee >(tr 1 a) | tr 1 b
.
- Output from the process substitutions will be unpredictably interleaved, and, except in zsh
, the pipeline may terminate before the commands inside >(…)
do.
在 unix(或 Mac)中,使用 tee
命令:
In unix (or on a mac), use the tee
command:
$ echo 123 | tee >(tr 1 a) >(tr 1 b) >/dev/null
b23
a23
通常你会使用 tee
将输出重定向到多个文件,但使用 >(...) 你可以重定向到另一个进程.所以,一般来说,
Usually you would use tee
to redirect output to multiple files, but using >(...) you can
redirect to another process. So, in general,
$ proc1 | tee >(proc2) ... >(procN-1) >(procN) >/dev/null
会做你想做的事.
在windows下,我不认为内置shell有等价物.Microsoft 的 Windows PowerShell 有一个 tee
命令虽然.
Under windows, I don't think the built-in shell has an equivalent. Microsoft's Windows PowerShell has a tee
command though.
这篇关于如何使用 Unix(或 Windows)中的(最好是未命名的)管道将一个进程的标准输出发送到多个进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!