Wednesday 5 June 2013

Get exit status of process that's piped to another

I have two processes foo and bar, connected with a pipe:
$ foo
bar
bar always exits 0;
I'm interested in the exit code of foo. Is there any way to get at it?

Ans:

There are 3 ways of doing this. However your current setup should work. The reason here being that the grep won't match anything if the command fails, so grep will return with status 1 (unless the program always shows that text no matter what).

Pipefail

The first way is to set the pipefail option. This is the simplest and what it does is basically set the exit status $? to the exit code of the last program to exit non-zero (or zero if all exited successfully).
# false |rue; echo $?
0
# set -o pipefail
# false |true; echo $?
1

$PIPESTATUS

Bash also has a variable called $PIPESTATUS which contains the exit status of all the programs in the last command.
# true |true; echo "${PIPESTATUS[@]}"
0 0
# false |true; echo "${PIPESTATUS[@]}"
1 0
# false |true; echo "${PIPESTATUS[0]}"
1
# true |false; echo "${PIPESTATUS[@]}"
0 1You can use the 3rd command example to get the specific value in the pipeline that you need.

This solution might not be available though. I think $PIPESTATUS might have been added in a fairly recent version of bash, and your OS may not have it.

Separate executions

This is the most unwieldy of the solutions. Run each command separately and capture the status
# OUTPUT="$(haconf -makerw)"
# STATUS_HACONF="$?"
# printf '%s' "$OUTPUT"
grep -iq "Cluster already writable"

0 blogger-disqus:

Post a Comment