I Want to Pipe My Output to Two Commands

syndicate said, “cat file |/sbin/command | /bin/command2” would be cool.

Yes, it would be cool. I thought maybe it would be possible by copying file descriptors, but I couldn’t quite figure that properly. The magic was in using a fifo.

Specifically large read operations should only be done once. Lets say we are reading an entire disk using dd, and sending that somewhere via netcat.

Normally we would just dd if=/dev/sda | netcat somewhere 1234

But it would be nice to compare the md5sum at both ends. If we run md5sum /dev/sda we get the md5sum, but now we have read the entire disk twice. That can take a long time. Lets only read it once!

The solution looks like this:

mkfifo myfifo ; dd if=/dev/sda | tee mkfifo | netcat somewhere 1234 & md5sum test

The data is sent to the fifo and netcat at the same time. The fifo is blocking so it is important to read from as soon as possible, so we start reading from it with md5sum immediately.

A solution on the receiving end to write the file and md5sum it immeidately is as easy at tee:

netcat -l -p 1234 | tee file | md5sum