Inform right-hand side of pipeline of left-side failure?

Bittrance picture Bittrance · Jul 3, 2011 · Viewed 7.8k times · Source

I've grown fond of using a generator-like pattern between functions in my shell scripts. Something like this:

parse_commands /da/cmd/file | process_commands

However, the basic problem with this pattern is that if parse_command encounters an error, the only way I have found to notify process_command that it failed is by explicitly telling it (e.g. echo "FILE_NOT_FOUND"). This means that every potentially faulting operation in parse_command would have to be fenced.

Is there no way process_command can detect that the left side exited with a non-zero exit code?

Answer

lethalman picture lethalman · Jul 12, 2013

Use set -o pipefail on top of your bash script so that when the left side of the pipe fails (exit status != 0), the right side does not execute.