How can I send the stdout of one process to multiple processes using (preferably unnamed) pipes in Unix (or Windows)?

secr picture secr · Sep 14, 2008 · Viewed 27.9k times · Source

I'd like to redirect the stdout of process proc1 to two processes proc2 and proc3:

         proc2 -> stdout
       /
 proc1
       \ 
         proc3 -> stdout

I tried

 proc1 | (proc2 & proc3)

but it doesn't seem to work, i.e.

 echo 123 | (tr 1 a & tr 1 b)

writes

 b23

to stdout instead of

 a23
 b23

Answer

dF. picture dF. · Sep 14, 2008

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.

In unix (or on a mac), use the tee command:

$ echo 123 | tee >(tr 1 a) >(tr 1 b) >/dev/null
b23
a23

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

will do what you want.

Under windows, I don't think the built-in shell has an equivalent. Microsoft's Windows PowerShell has a tee command though.