我需要我的cronjob仍然继续输出一些文件中的错误,但我也希望他们同时通过电子邮件发送。 这似乎不可能没有一些技巧。
我发现这一点,但没有帮助我。
什么是最简单的方法来做到这一点?
如果我正确理解你的问题,你想发送错误(不输出)到日志文件,并通过电子邮件发送。
为此,请使用tee和stdout / stderrredirect的组合。
根据cron(8)手册页,cron可以为您处理电子邮件。 不需要重复这个努力。
当执行命令时,任何输出都被发送到crontab的所有者(或者crontab中的MAILTO环境variables中命名的用户,如果存在的话)。
这里的技巧是将STDERR发送到日志文件并发送电子邮件,而不是STDOUT。 以下示例说明如何执行此操作。
假设我的脚本执行下面的命令。 ls tmp/foo成功,所以这个输出转到STDOUT。 ls tmp/bar产生一个错误,所以这个输出被发送到STDERR。
$ ls tmp/foo tmp/bar ls: tmp/bar: No such file or directory tmp/foo
以下cronjob将隐藏任何STDOUT,但会将STDERRredirect到/var/log/test.log
* * * * * ls tmp/foo tmp/bar 2>&1 >/dev/null | tee -a $HOME/var/log/test.log
这是结果。 电子邮件和〜/ var / log / test.log都会说同样的事情。
电子邮件正文说:
ls: tmp/bar: No such file or directory
日志文件说了同样的事情:
$ cat ~/var/log/test.log ls: tmp/bar: No such file or directory
作为一个额外的好处,也可以发送STDERR&STDOUT到一个日志文件(你只是偶尔看),但是发送STDERR到屏幕(如果手工运行)或者电子邮件(如果从cron运行)。 对于长时间运行的构build脚本,我使用以下snippit。
{ { ./configure && make && make install ; } >> $LOGFILE ; } 2>&1 | tee -a $LOGFILE
使用tee :
MBPro-ABustardo:~ abustardo$ echo foo |tee tmp foo MBPro-ABustardo:~ abustardo$ cat tmp foo
在你的情况下:
[your script] 2>&1 |tee [some local local file] |mail -s [subject] [email protected]
这回答了你的问题了吗? https://stackoverflow.com/questions/1396506/cron-send-email-with-stderr-but-not-stdout
除非定向到/dev/null否则Cron应该在每次运行后发送一封电子邮件