Redirect crontab output to email

17,982

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
Share:
17,982

Related videos on Youtube

Frida
Author by

Frida

Updated on September 18, 2022

Comments

  • Frida
    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.
    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
    James O'Gorman over 11 years
    It'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.
    R. S. over 11 years
    You can still use tee in your scripting as well rather then mucking with temporary files.
  • James O'Gorman
    James O'Gorman over 11 years
    TIMTOWTDI. 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.