Alex Rivera | Logout

bash script: how to save return value of first command in a pipeline?

Asked 2011-05-10T19:50:31.130
9

Bash: I want to run a command and pipe the results through some filter, but if the command fails, I want to return the command's error value, not the boring return value of the filter:

E.g.:

if !(cool_command | output_filter); then handle_the_error; fi

Or:

set -e
cool_command | output_filter

In either case it's the return value of cool_command that I care about -- for the 'if' condition in the first case, or to exit the script in the second case.

Is there some clean idiom for doing this?

Edit
Report

1 Answer

16

Use the PIPESTATUS builtin variable.

From man bash:

PIPESTATUS

An array variable (see Arrays below) containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command).

answered 2011-05-10T20:29:15.670

Your Answer