Search code examples
linuxcronpostfix-mta

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


I have a problem with the error mail's from cron
If I create two job's executing the same perl script one which redirected to /dev/null or a logfile and one without redirect I only get an error mail for the one without redirect

/etc/cron.d/test-cron

MAILTO="[email protected]"
*   *   *   *   *   root    /root/test.sh > /dev/null
*   *   *   *   *   root    /root/test.sh
/root/test.sh

#!/usr/bin/perl
use strict;

print "test\n";
exit 1;

syslog output for cron and 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@[email protected]>
May 18 19:14:01 cron-master postfix/qmgr[143]: 5537251A9: from=<[email protected]>, size=674, nrcpt=1 (queue active)
May 18 19:14:01 cron-master postfix/smtp[30968]: 5537251A9: to=<[email protected]>, 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
  • cron -> 3.0pl1-136ubuntu1
  • postfix -> 3.4.10-1ubuntu1
  • OS -> latest Ubuntu 20.04 docker image (ubuntu:focal-20200423)
  • Docker Endpoint -> /usr/sbin/cron -f -l -L 15

Solution

  • You can use tee command to "fork" standard output.

    *   *   *   *   *   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