Shell One Liner: Find failed processes in pipe with pipestatus

A problem with pipes is that they can fail silently since each command in it runs as its own process independent from the rest. So the pipe as a total does not return an error (non-zero exit code) to signal if one of the processes failed.  This is particularly a problem in cron jobs where you usually don’t examine the outcome. A solution can be to examine the exit codes of all processes after the pipe finished. $PIPESTATUS is a variable available in some shells that collects the exit codes from all pipe processes. A simple one-liner will show you all the non-zero exit codes.

$ ls|grep "will-fail"|tail -n10;for i in "${PIPESTATUS[@]}"; do if [ "$i" != "0" ]; then echo "A process in the pipe exited with error code:"$i;fi;done;

Another approach to the problem can be to redirect inputs and outputs with ‘<‘, ‘>’, and ‘>>’ to run everything in one process. Of course, this is not equivalent and only applicable in some cases.

Leave a Reply




This site uses Akismet to reduce spam. Learn how your comment data is processed.