Cron: mail only when things go wrong

From FVue
Jump to: navigation, search


Only when things go wrong, I want to receive an e-mail from cron.


Specify this as the cron job: >> logfile 2>&1 || echo "Error occurred.  See $(pwd)/log for details"

Explanation: Both stderr and stdout are redirected to a logfile. If 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

Bash: Catch error



I was thinking about redirecting only stderr to screen, and both stdout and stderr to a log file.

Example file

echo stderr A >&2
echo stdout
echo stderr B >&2
exit 1

From SHELLdorado - Shell Tips & Tricks (Advanced), I found this solution:

((bash 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

I would like the output of mix.txt to be the output of bash 2>&1:

stderr A
stderr B


blog comments powered by Disqus