Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I need my cronjobs to still continue to output errors in some files, but I also want them to be emailed at the same time. That doesn't seem to be possible without some tricks.

I found this but didn't helped me.

What would be the most simple way to do that ?

share|improve this question

3 Answers 3

up vote 4 down vote accepted

If I understand your question correctly, you want to send the errors (not output) to a logfile, and also send them via email.

To do this, use a combination of tee and stdout/stderr redirection.

According to the cron(8) manpage, cron can handle the email for you. No need to duplicate this effort needlessly.

When executing commands, any output is mailed to the owner of the crontab (or to the user named in the MAILTO environment variable in the crontab, if such exists).

The trick here is to send STDERR to a logfile and to email, but not STDOUT. The following example illustrates how to do this.

Assume that my script executes the following command. ls tmp/foo is successful, so this output goes to STDOUT. ls tmp/bar generates an error, so this output is sent to STDERR.

$ ls tmp/foo tmp/bar
ls: tmp/bar: No such file or directory
tmp/foo

The following cronjob will hide any STDOUT, but will redirect STDERR to /var/log/test.log

* * * * * ls tmp/foo tmp/bar 2>&1 >/dev/null | tee -a $HOME/var/log/test.log

Here are the results. The email and ~/var/log/test.log will both say the same thing.

The email body says:

ls: tmp/bar: No such file or directory

The logfile says the same thing:

$ cat ~/var/log/test.log
ls: tmp/bar: No such file or directory

As an added bonus, it is also possible to send STDERR & STDOUT to a logfile (which you only look at occasionally), but send STDERR to the screen (if run by hand) or email (if run from cron). I use the following snippit for long-running buildscripts.

{ { ./configure && make && make install ; } >> $LOGFILE ; } 2>&1 | tee -a $LOGFILE
share|improve this answer

Use tee:

MBPro-ABustardo:~ abustardo$ echo foo |tee tmp  
foo

MBPro-ABustardo:~ abustardo$ cat tmp  
foo

in your case:

[your script] 2>&1 |tee [some local local file] |mail -s [subject] foo@example.com
share|improve this answer

Does this answer your question? http://stackoverflow.com/questions/1396506/cron-send-email-with-stderr-but-not-stdout

Cron is supposed to send an email after each run unless directed to /dev/null

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.