Bash tip: idiom to get the first error code from a pipe

When writing a bash script, often times you’ll end up with something like this:

real_command | filter_stuff | prettify | do_something_else

The problem arises when you try to figure out if your command succeeded or not. If you `echo $?` you’ll get the return code for the last chain in the pipe. You don’t really care about the output value of do_something_else, do you?

I haven’t found a solution I really like to this problem, but this idiom is handy:

out=`real_command` && echo $out | filter_stuff | prettify | do_something_else

echo $?

Now $? will hold the value of real_command, and you can actually use it to diagnose the real problem.

Advertisements

One Comment on “Bash tip: idiom to get the first error code from a pipe”

  1. denisss025 says:

    Have you tried set -o pipefail? Here is the description.

    If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully. This option is disabled by default.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s