Redirect crontab output to email
The cron entry you have there is redirecting both STDOUT
and STDERR
to a file: /var/log/CRONLOGS/testing_prod.log
.
The simplest method to do what you want would be to run mailx
at the end of the cron job, using indirection to send that file:
00 06 * * * /usr/bin/php /home/user/myapp/testing.sh -e prod 1>> /var/log/CRONLOGS/testing_prod.log 2>&1; mailx -s "Cron output" [email protected] < /var/log/CRONLOGS/testing_prod.log
However: take note that your cron job is appending to the log file, so unless it's being purged of old entries (or rotated) regularly, you'll receive all previous output as well as new output. It would probably be best to create a small shell script to write to a temporary log, mail it, then append it to the mail log:
#!/bin/sh
/usr/bin/php /home/user/myapp/testing.sh -e prod 1>> /tmp/testing_prod$$.log 2>&1
mailx -s "Cron output" [email protected] < /tmp/testing_prod$$.log
cat /tmp/testing_prod$$.log >> /var/log/CRONLOGS/testing_prod.log
rm /tmp/testing_prod$$.log
This has the benefit of making the crontab
look tidier:
00 06 * * * /home/user/myapp/cronscript.sh
Related videos on Youtube
Frida
Updated on September 18, 2022Comments
-
Frida over 1 year
It looks simple but how can I redirect output of this kind of crontab to my email?
00 06 * * * /usr/bin/php /home/user/myapp/testing.sh -e prod 1>> /var/log/CRONLOGS/testing_prod.log 2>&1
I've try to add [email protected] but without any results.
Regards
-
R. S. over 11 years
tee
is a much better solution as it will still append to the log file and also only email out the new data without needing a temporary file. -
James O'Gorman over 11 yearsIt's a solution. Personally I prefer to script it so that I can have a custom subject and mail recipient. The mail could also include diagnostic info, if required, along with the logs.
-
R. S. over 11 yearsYou can still use
tee
in your scripting as well rather then mucking with temporary files. -
James O'Gorman over 11 yearsTIMTOWTDI. There's nothing wrong with temporary files, but sure, tee would also work in this instance. Either way I tend to prefer scripts so that the
crontab
isn't cluttered and unreadable.