Search code examples
bashshellpipexargstee

How to break pipe if stdin is empty?


I want to break the whole pipe if the stdin is empty. I try to combined xargs -r and tee, which means not print and write if stdin is empty, but it failed

...| upstream commands | xargs -r tee output.txt | downstream commands | ...

Any feedback appreciated.


Solution

  • There is no way you can actually terminate a bash pipe conditionally. All commands in a pipeline are started simultaneously. There is however a tool available that would assist you with creating a conditional pipeline. In moreutils you can find the tool ifne which executes a command if and only if the input /dev/stdin is not empty. So you could write something like:

    $ command1 | ifne command2 | ifne command3 | ifne command4
    

    Here all commands ifne and command1 are started simultaniously. Only if ifne receives input via /dev/stdin, it will start its respective commandx