3

Is it possible to run a command to redirect output and standard error in a file and know the return code of the command ?

./COMMANDE.sh 2>&1 | tee -a $LOG_DIRECTORY/$LOG_FILE
if [ $? = 0 ]; then
    echo "OK"
else
    echo "KO"
    exit 1
fi

Currently, I get the return code of the tee command, I want to recover that of COMMANDE.sh.

1 Answer 1

3

You want PIPESTATUS.

./COMMANDE.sh 2>&1 | tee -a $LOG_DIRECTORY/$LOG_FILE
if [ ${PIPESTATUS[0]} = 0 ]; then
    echo "OK"
else
    echo "KO"
    exit 1
fi

The index into the array ([0]) is the index of the command in the pipe chain just executed (./COMMANDE.sh). ${PIPESTATUS[1]} would be the tee.

Sign up to request clarification or add additional context in comments.

1 Comment

@davidcondrey pointed out that zsh has a similar construct pipestatus that starts counting array indices at 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.