Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cron: sending output to file then EMAILing file to me

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

like image 511
oompahloompah Avatar asked Mar 28 '11 07:03

oompahloompah


People also ask

Where do cron errors go?

On Ubuntu, Debian and related distributions, you will find cron jobs logs in /var/log/syslog .

What email does cron use?

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.

How do I stop my cron job from automatically running?

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.


1 Answers

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]
like image 162
sarnold Avatar answered Oct 07 '22 01:10

sarnold