Search code examples
shellpipestdouttee

Pipe output to two different commands not interlaced


Using techniques mentioned here (Pipe output to two different commands) we can split a stdout into multiple processes.

expensive_command | tee >(proc_1) >(proc_2) | proc_3

my problem is this interlaces the output.

Is there a way to copy the stdout but force proc_2 to block until proc_1 finishes?

I'm thinking something like

expensive_command | tee >(proc_1) | wait for EOF | tee >(proc_2) ...

Solution

  • You can use a fifo as a cheap lock. Have proc1 write to it after it completes, and wait until a read from the fifo succeeds before running proc2.

    mkfifo cheap_lock
    expensive_command | tee >(proc1; echo foo > cheap_lock) \
                            >(read < cheap_lock; proc2 ) | proc3
    

    (Of course, it's your responsibility to ensure that no other processes try to read from or write to cheap_lock.)