我有一个cron工作,我想发送它的输出到/dev/null
但如果发生错误,那么它应该发送一封电子邮件。
否则,我会每天收到cron的输出的电子邮件,而且我很难看到错误何时发生。
怎么样
59 23 * * * { tmpFile=/tmp/yourCmdErrs.$$ ; export tmpFile ; yourCommand > /dev/null 2>${tmpFile}; if [ -s ${tmpFile} ] ; then mailx -s"errors in yourCommand" < ${tmpFile} ; /bin/rm ${tmpFile} ; fi ; }
爆炸,它是
# set whatevery your time/days are # 59 23 * * * # my superstition to use open and closing # { } # set a tmpFile var # tmpFile=/tmp/yourCmdErrs.$$ ; export tmpFile ; # run yourCmd save STDERR to file # yourCommand > /dev/null 2>${tmpFile}; # check if tmpFile has anything in it # if [ -s ${tmpFile} ] ; then # obvious, hopefully # mailx -s"errors in yourCommand" < ${tmpFile} # cleanup tmpFile # /bin/rm ${tmpFile} ; # fi # note that closing ';' is a must when using {} pairs ; }
实际的邮件/ mailx调用可能会有点时髦,我现在没有办法测试它。
我希望这有帮助。
建议你简单的修改你从cron调用的脚本的输出到管道stdout到/ dev / null:所有的输出到/ dev / null, stderr进入MAILTO目标。
my_program 2>&1 1>/dev/null | mailx -s "Subject" recipient ...
虽然违反直觉(对我来说),重定向似乎是从右到左由shell处理。 这个序列首先抛出标准输出, 然后将标准错误重定向到标准输出。