-1

I'm running a script that executes a command and save the output to a file in /var/log. After that, it gets the exit code and execute another command based on an if/else condition. The problem is: 2>&1 | tee -a /var/log/file.log always returns 0, no matter the real exit code from the command.

How to work around this problem?

Piece of the code:

rdiff-backup --force /localdir external.domain"::/backups/externaldir 2>&1 | tee -a /var/log/file.log
e="$(echo $?)"
if [ "$e" == "0" ]; then
        echo "`date` Done." 2>&1 | tee -a /var/log/file.log
else
        echo "`date` Fail!" 2>&1 | tee -a /var/log/file.log            
fi
1

This is because the exit code of a pipe is the exit code of the last stage of a pipe, and tee never fails :)

This can be solved different ways depending on your shell. https://unix.stackexchange.com/questions/14270/get-exit-status-of-process-thats-piped-to-another collects many answers.

  • Would you care to suggest one of the ways to solve the problem? – Michael Hampton Oct 18 '18 at 5:19
  • Thank you, Sir. Your link helped me a lot. I'm using set -o pipefail now. With this, if a command returns false | true, it will return false. (Chris' answer) – Mateus Scheper Oct 18 '18 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.