I am writing a series of cron jobs. I want each task to log its output to file, and then I want the contents of the file mailed to me at say [email protected]
I think logging the output to file can be done using simple pipe redirection like this:
30 0 * * * /path/to/script1 > task1.log
30 1 * * * /path/to/script2 > task2.log
However, I am not sure how to mail the files (or simply their contents) to me in seperate emails to [email protected]
Also, is there a way to dynamically create the log file names, based on the date, so that the log names would be something like %Y%m%d.task1.log ?
Where the prefix is the date ?
I am running on Ubuntu 10.0.4 LTS
On Ubuntu, Debian and related distributions, you will find cron jobs logs in /var/log/syslog .
In https://unix.stackexchange.com/a/479613/674, Stephen mentioned that cron uses MTA (such as postfix or sendmail) to send the outputs of its jobs as emails.
Stop a cron job You can stop a single cron job by removing its line from the crontab file. To do that, run the crontab -e command and then delete the line for the specific task.
If your system has a working /usr/bin/sendmail
(doesn't have to be sendmail sendmail
, most mail servers provide a /usr/bin/sendmail
wrapper script) then you can use the mail(1)
utility to send mail:
echo "hello world" | mail -s hello [email protected]
mail(1)
is pretty primitive; there's no MIME file attachments, you're stuck with plaintext.
If mutt(1)
is installed, you can use MIME to attach files:
echo "hello world" | mutt -a task*.log -- [email protected]
As for giving the logfiles dates:
$ echo "hi" > $(date "+%Y%m%dlog.txt")
$ cat 20110328log.txt
hi
$
So, try this:
30 1 * * * /path/to/script2 > $(date "+\%Y\%m\%dlog.txt") && mutt -a $(date "+\%Y\%m\%dlog.txt") -- [email protected]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With