Shell pipe: Exit immediately when one command fails

前端 未结 5 979
长发绾君心
长发绾君心 2020-12-28 15:09

I\'m using a pipe of several commands in bash. Is there a way of configuring bash to terminate all commands in the whole pipeline immediately should one of the commands fail

5条回答
  •  伪装坚强ぢ
    2020-12-28 15:29

    The first program does not know whether the second is terminated or not until it tries to write some date into the pipe. In case the second is terminated, the first receives the SIGPIPE which usually causes immediate exit.

    You can force the first line of output to be piped immediately after staring, like this:

    (sleep 0.1; echo; command1) | command2
    

    This 100ms sleep is intended to wait until possible command2 exit right after starting. Of course, if command2 exits after 2 seconds, and command1 will be silent for 60 seconds, the whole shell command will return only after 60.1 seconds.

提交回复
热议问题