Pipe output to two different commands [duplicate]

2020-02-07 18:42发布

问题:

This question already has answers here:
Closed 7 years ago.

Possible Duplicate:
osx/linux: pipes into two processes?

Is there a way to pipe the output from one command into the input of two other commands, running them simultaneously?

Something like this:

$ echo 'test' |(cat) |(cat)
test
test

The reason I want to do this is that I have a program which receives an FM radio signal from a USB SDR device, and outputs the audio as raw PCM data (like a .wav file but with no header.) Since the signal is not music but POCSAG pager data, I need to pipe it to a decoder program to recover the pager text. However I also want to listen to the signal so I know whether any data is coming in or not. (Otherwise I can't tell if the decoder is broken or there's just no data being broadcast.) So as well as piping the data to the pager decoder, I also need to pipe the same data to the play command.

Currently I only know how to do one - either pipe it to the decoder and read the data in silence, or pipe it to play and hear it without seeing any decoded text.

How can I pipe the same data to both commands, so I can read the text and hear the audio?

I can't use tee as it only writes the duplicated data to a file, but I need to process the data in real-time.

回答1:

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

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


回答2:

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


回答3:

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 will pass hello as argument to <some_command>.