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.
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. Puttingset -o pipefail
above the pipe affects to the exit status of the pipeline. – jarno May 16 '20 at 19:13