Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring Bash pipefail for error code 141

Tags:

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?

like image 635
Alex Reynolds Avatar asked Mar 17 '14 20:03

Alex Reynolds


3 Answers

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
like image 190
Doctor J Avatar answered Oct 01 '22 03:10

Doctor J


The trap command lets you specify a command to run when encountering a signal. To ignore a signal, pass the empty string:

trap '' PIPE
like image 40
chepner Avatar answered Oct 01 '22 04:10

chepner


There isn't a way that I know of to do this for the whole script. It would be risky in general, since there's no way to know that a child process didn't return 141 for a different reason.

But you can do this on a per-command basis. The || 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!'
like image 41
Jack O'Connor Avatar answered Oct 01 '22 04:10

Jack O'Connor