Cron job stderr to email AND log file?

前端 未结 9 1623
离开以前
离开以前 2021-01-06 07:57

I have a cron job:

$SP_s/StartDailyS1.sh >$LP_s/MirrorLogS1.txt

Where SP_s is the path to the script and LP_s

相关标签:
9条回答
  • 2021-01-06 08:53

    I think the solution would be:

    $SP_s/StartDailyS1.sh 2>&1 >> $LP_s/MirrorLogS1.txt | tee -a $LP_s/MirrorLogS1.txt
    

    This will:

    • append standard output to $LP_s/MirrorLogS1.txt
    • append standard error to $LP_s/MirrorLogS1.txt
    • print standard error, so that cron will send a mail in case of error
    0 讨论(0)
  • 2021-01-06 08:56

    Since I was just looking at the info page for tee (trying to figure out how to do the same thing), I can answer the last bit of this for you.

    This is most of the way there:

    (( my_command 3>&1 1>&2 2>&3 ) | tee error_only.log ) > all.log 2>&1
    

    but replace "error_only.log" with ">(email_command)"

    (( my_command 3>&1 1>&2 2>&3 ) | tee >(/bin/mail -s "SUBJECT" "EMAIL") ) > all.log 2>&1
    

    Note: according to tee's docs this will work in bash, but not in /bin/sh. If you're putting this in a cron script (like in /etc/cron.daily/) then you can just but #!/bin/bash at the top. However if you're putting it as a one-liner in a crontab then you may need to wrap it in bash -c ""

    0 讨论(0)
  • 2021-01-06 08:56

    Unless I'm missing something:

    command 2>&1 >> file.log | tee -a file.log
    

    2>&1 redirects stderr to stdout

    >> redirects regular command stdout to logfile

    | tee duplicates stderr (from 2>&1) to logfile and passes it through to stdout be mailed by cron to MAILTO

    I tested it with

    (echo Hello & echo 1>&2 World) 2>&1 >> x | tee -a x
    

    Which indeed shows World in the console and both texts within x

    The ugly thing is the duplicate file name. And the different buffering from stdout/stderr might make text in file.log a bit messy I guess.

    0 讨论(0)
提交回复
热议问题