Ignoring bash pipefail for error code 141

Setting the bash pipefail parameter (via set -o pipefail ) allows the script to crash if a non-zero error is detected, where at any point in the pipe there is a non-zero error.

However, we encounter SIGPIPE errors (error code 141), where data is written to a channel 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 example, in Python, we can add:

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

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

Is there a similar option in bash?

+6
source share
3 answers

The trap command allows you to specify a command to run when a signal is encountered. To ignore the signal, skip the empty line:

 trap '' PIPE 
+6
source

I process this on each pipeline, binding to the || if ... operator || if ... to swallow exit code 141, but still encountering any other errors:

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

I do not know how to do this for the whole script. This would be risky overall, as there is no way to find out that the child process did not return 141 for another reason.

But you can do this based on each team. Operator || suppresses any errors returned by the first command, so you can do something like:

 set -e -o pipefail (cat /dev/urandom || true) | head -c 10 | base64 echo 'cat exited with SIGPIPE, but we still got here!' 
+2
source

All Articles