Thursday, February 3, 2022

[SOLVED] How to read return code of command when piped with another command

Issue

I have a bash script where I execute a command and tee to a file. On checking the return code, it is always 0 which is for the tee <> command.

make all | tee output.log
if [[ $? -ne 0 ]]; then
    echo "Make failed"
    exit 1
else
    blah blah
fi

Is there a way to check the return code of the first command (i.e. make all in this case)?


Solution

Suppose you have the commands pipe command1 | command2, you can get each command exit code by:

echo "${PIPESTATUS[0]} - ${PIPESTATUS[1]}"


Answered By - Antonio Petricca
Answer Checked By - Timothy Miller (WPSolving Admin)