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
Best Answer
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.