Cron: mail only when things go wrong
From FVue
Problem
Only when things go wrong, I want to receive an e-mail from cron.
Solution
Specify this as the cron job:
cronjob.sh >> logfile 2>&1 || echo "Error occurred. See $(pwd)/log for details"
Explanation: Both stderr and stdout are redirected to a logfile. If cronjob.sh exits with an error, an error message is written to stdout, which cron will mail automatically to the cron owner. Specify MAILTO=username@domain if you want mail to be sent to an alternate address.
See also
Journal
20060529
I was thinking about redirecting only stderr to screen, and both stdout and stderr to a log file.
Example file t.sh:
echo stderr A >&2 echo stdout echo stderr B >&2 exit 1
From SHELLdorado - Shell Tips & Tricks (Advanced), I found this solution:
((bash t.sh 2>&1 1>&3 | tee ~/err.txt) 3>&1 1>&2 | tee ~/out.txt) > ~/mix.txt 2>&1
but in mix.txt stderr is shown after stdout:
stderr A stderr B stdout
I would like the output of mix.txt to be the output of bash t.sh 2>&1:
stderr A stdout stderr B
Advertisement