6

I asked this question. SIGPIPE signal is generated to stop the execution of the command as told in the answer.

But how do I capture this signal and gracefully terminate the command? The command exits with an error saying that it is a broken pipe.

[ERROR] [Errno 32] Broken pipe

is the error message displayed

1 Answers1

6

AFAIK, the only way to "catch" a signal like this is to use the trap command. Which you specifically setup an action (function or command(s)) to run when a particular signal is received.

Example

#!/bin/bash


cleanup () {
    ...do cleanup tasks & exit...
}

trap "cleanup" SIGPIPE

### MAIN part of script

This approach could just as easily be in a single one-liner vs. a script. The "function" that is called, cleanup, when SIGPIPE is seen could just as easily be a elaborate one-liner too.

$ trap "cmd1; cmd2; cmd3;" SIGPIPE

If you look back at the original question you linked to: Terminating an infinite loop, you'll notice that this approach is even represented there as well.

slm
  • 369,824
  • sorry, didn't see that answer. Thank you – user2555595 Sep 05 '14 at 10:53
  • 1
    @user2555595 - NP. If you don't know what traps are, they're easy to disregard. I only learned about how to actual use them myself, this past month 8-). – slm Sep 05 '14 at 11:02
  • I tried that code, and put yes | head -n 10 in the "MAIN part". But the cleanup will be never called. Besides, if you call the script like (trap '' SIGPIPE; ./script) in shell the broken pipe message will be shown. Putting set -o pipefail above the pipe affects to the exit status of the pipeline. – jarno May 16 '20 at 19:13