Take the 2-minute tour ×

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:


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


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?

share|improve this question
add comment

4 Answers

Use the PIPESTATUS builtin variable.

From man bash:



share|improve this answer
add comment

If you didn't need to display the error output of the command, you could do something like

if ! echo | mysql $dbcreds mysql; then
    error "Could not connect to MySQL. Did you forget to add '--db-user=' or '--db-password='?"
    die "Check your credentials or ensure server is running with /etc/init.d/mysqld status"

In the example, error and die are defined functions. elsewhere in the script. $dbcreds is also defined, though this is built from command line options. If there is no error generated by the command, nothing is returned. If an error occurs, text will be returned by this particular command.

Correct me if I'm wrong, but I get the impression you're really looking to do something a little more convoluted than

[ `id -u` -eq '0' ] || die "Must be run as root!"

where you actually grab the user ID prior to the if statement, and then perform the test. Doing it this way, you could then display the result if you choose. This would be

UID=`id -u`
if [ $UID -eq '0' ]; then
    echo "User is root"
    echo "User is not root"
    exit 1 ##set an exit code higher than 0 if you're exiting because of an error
share|improve this answer
add comment

Execute your commands like this:

s=$(cool_command) && echo $s | output_filter 

That way when you do echo $? afterwards you will see return status of cool_command if it fails.

share|improve this answer
add comment

The following script uses a fifo to filter the output in a separate process. This has the following advantages over the other answers. First, it is not bash specific. In particular it does not rely on PIPESTATUS. Second, output is not stalled until the command has completed.

$ cat >test_filter.sh <<EOF

    echo $1
    echo $2 >&2
    return $3

    while read line
            echo "... $line"

tmpdir=$(mktemp -d)
mkfifo "$fifo"

filter <"$fifo" &
cmd a b 10 >"$fifo" 2>&1
wait $pid
echo exit code: $ret
rm -f "$fifo"
rmdir "$tmpdir"
$ sh ./test_filter.sh
... a
... b
exit code: 10
share|improve this answer
add comment

Your Answer


