LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Print stdout and stderr to screen + log file and catch any errors in shell script (https://www.linuxquestions.org/questions/linux-general-1/print-stdout-and-stderr-to-screen-log-file-and-catch-any-errors-in-shell-script-4175455771/)

idaham 03-27-2013 07:29 AM

Print stdout and stderr to screen + log file and catch any errors in shell script
 
Hello!
I'm writing a shell script that executes a command. I want to save both stdout and stderr to the same log file + print to sceen and at the same time catch if there is an error. What I have so far is:
Code:

set -o pipefail
errorsFound=0
command arg1 arg2 2>&1 | tee logFile.log || errorsFound=1
if [[ $errorsFound == 1 ]]; then
        echo "command failed!"
        exit 1
fi

When I run the shell script the logFile.log is created and seems to contain all the output information. However, the variable "errorsFound" always turns to 1, even though there are no errors from the command. Have I set this up wrong?
Thanks in advance!

pan64 03-27-2013 08:25 AM

yes, tee will eat up the error code.
try the following:
Code:

set -o pipefail
errorsFound=0
{
command args 2>&1 || {
    echo command failed
    exit 1
}
} | tee logfile


chrism01 03-28-2013 04:32 AM

Incidentally, '==' is a string comparator; you'd want '-eq'
http://tldp.org/LDP/abs/html/comparison-ops.html

idaham 03-28-2013 06:43 AM

Thank you pan64, your solution worked just fine! I used the code below
Code:

set -o pipefail
errorsFound=0
{
command args 2>&1 || { errorsFound=1; }

if [[ $errorsFound == 1 ]]; then { echo "command failed"; exit 1; } fi
} | tee logfile



All times are GMT -5. The time now is 04:38 AM.