0

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
Gonçalo Peres
  • 145
  • 1
  • 2
  • 10
Asdra
  • 105
  • 1
  • 3
  • 12

1 Answers1

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.

pjz
  • 10,497
  • 1
  • 31
  • 40
  • Would you care to suggest one of the ways to solve the problem? – Michael Hampton Oct 18 '18 at 05: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)](https://unix.stackexchange.com/a/14282/298547) – Asdra Oct 18 '18 at 13:01