如果命令输出重定向到日志文件,cron 将停止发送错误邮件

cron stop sending error mails if command output is redirected to logfile

我对来自 cron 的错误邮件有疑问
如果我创建两个执行相同 perl 脚本的作业,一个重定向到 /dev/null 或日志文件,另一个没有重定向,我只会收到一封没有重定向的错误邮件

/etc/cron.d/test-cron

MAILTO="logs@example.com"
*   *   *   *   *   root    /root/test.sh > /dev/null
*   *   *   *   *   root    /root/test.sh
/root/test.sh

#!/usr/bin/perl
use strict;

print "test\n";
exit 1;

cron 和 postfix 的系统日志输出

May 18 19:14:01 cron-master CRON[31428]: (root) CMD ([31436] /root/test.sh)
May 18 19:14:01 cron-master CRON[31428]: (CRON) error (grandchild #31436 failed with exit status 1)
May 18 19:14:01 cron-master CRON[31428]: (root) END ([31436] /root/test.sh)
May 18 19:14:01 cron-master CRON[31429]: (root) CMD ([31439] /root/test.sh > /dev/null)
May 18 19:14:01 cron-master CRON[31429]: (CRON) error (grandchild #31439 failed with exit status 1)
May 18 19:14:01 cron-master CRON[31429]: (root) END ([31439] /root/test.sh > /dev/null)
May 18 19:14:01 cron-master postfix/pickup[28859]: 5537251A9: uid=0 from=<root>
May 18 19:14:01 cron-master postfix/cleanup[30966]: 5537251A9: message-id=<20200518191401.5537251A9@cron-master@example.com>
May 18 19:14:01 cron-master postfix/qmgr[143]: 5537251A9: from=<cron-master@example.com>, size=674, nrcpt=1 (queue active)
May 18 19:14:01 cron-master postfix/smtp[30968]: 5537251A9: to=<logs@example.com>, relay=smtp.example.com[80.50.67.97]:587, delay=0.42, delays=0.02/0/0.32/0.09, dsn=2.0.0, status=sent (250 Requested mail action okay, completed: id=1Ma1oK-1jXP8H2tyW-00W08q)
May 18 19:14:01 cron-master postfix/qmgr[143]: 5537251A9: removed

您可以使用 tee 命令来 "fork" 标准输出。

*   *   *   *   *   root    /root/test.sh | tee -a logfile_name

man tee

tee - read from standard input and write to standard output and files
Synopsis
tee [OPTION]... [FILE]...
Description
Copy standard input to each FILE, and also to standard output.

-a, --append
append to the given FILEs, do not overwrite