0

In macOS, cronjobs configured with crontab have the command output and/or error messages (if the cron doesn't succeed) written to the /var/mail/$USER file. Can this be prevented? I've tried:

* * * * *      /sbin/ping -c1 website.com ... 2>&1 >/dev/null

Whether it succeeds or fails to reach the domain, the ping output is saved to the mail file...

3

The cron daemon does not write to /var/mail/$USER, it sends an email to the user whenever a job outputs anything or fails, which in turn is written to that file (the user's mail inbox) by the system's mail delivery service.

To turn off the sending of email from the cron daemon, set the MAILTO variable to an empty value in the crontab file:

MAILTO=""

# rest of file with job schedules goes here

From the crontab(5) manual on a macOS system:

In addition to LOGNAME, HOME, and SHELL, cron(8) will look at MAILTO if it has any reason to send mail as a result of running commands in "this" crontab. If MAILTO is defined (and non-empty), mail is sent to the user so named. If MAILTO is defined but empty (MAILTO=""), no mail will be sent. [...]

If you turn off mailing of job output and error notifications in this way, you may want to log the job in some other way, for example,

* * * * *      /sbin/ping -c1 website.com ... >>/tmp/ping.log 2>&1
0 0,12 * * *   mv /tmp/ping.log /tmp/ping.log.old

This would add the output of ping to a specific file, and also move that file away at midnight and noon (note that your redirections to /dev/null was back-to-front).

You may also want to explicitly send an email if the ping fails:

* * * * *      /sbin/ping -c1 website.com ... >>/tmp/ping.log 2>&1 || mail -s "ping failed, do something" "$LOGUSER"

This would send an empty email with the specified title whenever ping returned a non-zero exit status.

Or, you could just get your redirections right from the start and don't bother with MAILTO or logfiles or sending emails:

* * * * *      /sbin/ping -c1 website.com ... >/dev/null 2>&1

This would send you an email whenever the ping failed, but would not send you the output of the command every minute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.