Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 963
George Young Avatar asked May 10 '11 19:05

George Young


1 Answers

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).

like image 68
Daenyth Avatar answered Nov 16 '22 01:11

Daenyth