Cronjob stderr to file and email
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 ?
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
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] [email protected]