Pipe output to two different commands

Maybe take a look at tee command. What it does is simply print its input to a file, but it also prints its input to the standard output. So something like:

echo "Hello" | tee try.txt | <some_command>

Will create a file with content "Hello" AND also let "Hello" (flow through the pipeline) end up as <some_command>'s STDIN.


Recent bash present >(command) syntax:

echo "Hello world." | tee >(sed 's/^/1st: /')  >(sed 's/^/2nd cmd: /') >/dev/null

May return:

2nd cmd: Hello world.
1st: Hello world.

download somefile.ext, save them, compute md5sum and sha1sum:

wget -O - http://somewhere.someland/somepath/somefile.ext |
    tee somefile.ext >(md5sum >somefile.md5) | sha1sum >somefile.sha1

or

wget -O - http://somewhere.someland/somepath/somefile.ext |
    tee >(md5sum >somefile.md5) >(sha1sum >somefile.sha1) >somefile.ext

Old answer

There is a way to do that via unnamed pipe (tested under linux):

 (( echo "hello" |
         tee /dev/fd/5 |
             sed 's/^/1st occure: /' >/dev/fd/4
    ) 5>&1 |
    sed 's/^/2nd command: /'
 ) 4>&1

give:

2nd command: hello
1st occure: hello

This sample will let you download somefile.ext, save them, compute his md5sum and compute his sha1sum:

(( wget -O - http://somewhere.someland/somepath/somefile.ext |
    tee /dev/fd/5 |
    md5sum >/dev/fd/4
  ) 5>&1 |
  tee somefile.ext |
  sha1sum
) 4>&1

It should be ok if you use both tee and mkfifo.

mkfifo pipe
cat pipe | (command 1) &
echo 'test' | tee pipe | (command 2)

Tags:

Bash

Pipe

Tee