如何将cron输出发送到null并将错误发送到电子邮件?

时间:2011-05-12 01:49:49

标签: linux bash

我有一个cron作业,我想将其输出发送到/dev/null,但如果发生错误,则应发送电子邮件。

否则我每天收到一封关于cron输出的电子邮件,我很难看到错误发生的时间。

3 个答案:

答案 0 :(得分:3)

建议你只需修改从cron到pipe stdout 调用的脚本输出到/ dev / null:所有输出都转到/ dev / null, stderr 转到MAILTO目标。

答案 1 :(得分:2)

怎么样

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 ; }

对mail / mailx的实际调用可能有点时髦,我现在无法测试它。

我希望这会有所帮助。

答案 2 :(得分:2)

my_program 2>&1 1>/dev/null | mailx -s "Subject" recipient ...

虽然反直觉(对我而言),重定向似乎是由shell从右到左处理的。此序列首先抛弃stdout 然后将stderr重定向到stdout。