在从Crontab发送电子邮件之前,请检查grep的输出是否为空

时间:2015-02-10 17:56:15

标签: bash email grep cron crontab

我在我的Crontab中有以下条目,grep我的日志中有任何错误,警告,通知等实例......

41 17 * * * cd /var/log/crmpicco-logs/; grep -E "error|Warning|Error|Notice|Fatal" $(find . -mtime 0 -type f) 2>&1 | mail -s "Errors/Warnings from Logs" info@ayrshireminis.com

我想要做的是调整它,以便只有mail搜索的输出返回结果才会执行grep命令。所以,如果它是空的,那么我不想收到电子邮件。

4 个答案:

答案 0 :(得分:2)

你可以让它有条件:

  

41 17 * * * cd /var/log/crmpicco-logs/; s=$(find . -mtime 0 -exec grep -E "error|Warning|Error|Notice|Fatal" {} +); [[ -n "$s" ]] && echo "$s" | mail -s "Errors/Warnings from Logs" info@ayrshireminis.com

答案 1 :(得分:2)

如果您对少一点感到满意,cron本身可以完成您想要的大部分工作。

MAILTO=info@ayrshireminis.com
41 17 * * * find /var/log/crmpicco-logs/ -mtime 0 -type f -exec grep -E "[Ee]rror|Warning|Notice|Fatal" {} +

如果没有输出,也没有电子邮件。

(主要因文体原因而重构。)

答案 2 :(得分:0)

来自man mail

   -E     If  an  outgoing message does not contain any text in its first or only message part, do not send it but discard it silently, effectively setting the skipemptybody variable at program startup.  This is useful for sending messages
          from scripts started by cron(8).

因此,我认为,只需在命令中添加-E键即可。

41 17 * * * cd /var/log/crmpicco-logs/; grep -E "error|Warning|Error|Notice|Fatal" $(find . -mtime 0 -type f) 2>&1 | mail -E -s "Errors/Warnings from Logs" info@ayrshireminis.com

答案 3 :(得分:-1)

if egrep -q "error|Warning|Error|Notice|Fatal" $(find . -mtime 0 -type f;then 
egrep "error|Warning|Error|Notice|Fatal" $(find . -mtime 0 -type f)|mail -s "Errors/Warnings from Logs" info@ayrshireminis.com
fi

以上代码grep -E与egrep(同一件事)

使用带有-q选项的egrep进行条件测试来抑制输出,一旦test为true然后执行命令而不抑制输出

相关问题