Ignoring Bash pipefail for error code 141

Alex Reynolds picture Alex Reynolds · Mar 17, 2014 · Viewed 9.1k times · Source

Setting the bash pipefail option (via set -o pipefail) allows the script to fail if a non-zero error is caught where there is a non-zero error in any step of a pipe.

However, we are running into SIGPIPE errors (error code 141), where data is written to a pipe that no longer exists.

Is there a way to set bash to ignore SIGPIPE errors, or is there an approach to writing an error handler that will handle all error status codes but, say, 0 and 141?

For instance, in Python, we can add:

signal.signal(signal.SIGPIPE, signal.SIG_DFL) 

to apply the default behavior to SIGPIPE errors: ignoring them (cf. http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-06/3823.html).

Is there some similar option available in bash?

Answer

Doctor J picture Doctor J · Oct 9, 2015

I handle this on a per-pipeline basis by tacking on an || if ... statement to swallow exit code 141 but still bubbling up any other errors:

pipe | that | fails || if [[ $? -eq 141 ]]; then true; else exit $?; fi