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

Check if output from grep is empty before sending email from 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

我想做的是调整它,以便它仅在 grep 搜索 returns 结果的输出时执行 mail 命令。所以,如果它是空的,那么我不想收到电子邮件。

你可以让它成为有条件的:

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

只要少一点你就满意了,cron本身就可以做到大部分你想做的

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

如果没有输出,也不会有邮件。

(主要出于文体原因进行了重构。)

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(一回事)

使用 egrep 和 -q 选项进行条件测试以抑制输出,一旦测试为真则执行命令而不抑制输出

来自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