[one-liner]: How do you capture the status of a command ($?) in Bash, when run through a pipe?

Background

While answering questions on the stackexchage website Unix & Linux I saw the following question which was about something I’d encountered, but until today never knew how to accomplish, so I’m posting it here for my own reference in the future.

The question?

How do you get the exit status ( $? ) from the command haconf -makerw in place of grep? i.e. what need to add in to my syntax in order to understand if haconf -makerw succeeded?

1
2
    haconf -makerw | grep -iq "Cluster already writable"
        # echo $? ( will print the exe status from haconf -makerw  )

Solution

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

1
2
3
4
5
# false | true; 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.

1
2
3
4
5
6
7
8
# true | true; echo "${PIPESTATUS[@]}"
0 0
# false | true; echo "${PIPESTATUS[@]}"
1 0
# false | true; echo "${PIPESTATUS[0]}"
1
# true | false; echo "${PIPESTATUS[@]}"
0 1

NOTE: You 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.

1
2
3
# OUTPUT="$(haconf -makerw)"
# STATUS_HACONF="$?"
# printf '%s' "$OUTPUT" | grep -iq "Cluster already writable"

References

links

NOTE: For further details regarding my one-liner blog posts, check out my one-liner style guide primer.

This entry was posted in bash, one-liner, script, shell, Syndicated, tips & tricks. Bookmark the permalink.

Comments are closed.