Get Messages From Crontab

Getting Messages from Crontab

We are used to getting messages, and crontab provides them in various ways: email, syslog, log files. Here are some ways you can configure crontab to tell you what’s going on:

Crontab Logging

You can create a new log, or append to an old log

Shell

1

2

3

4

5

#Create new log file each time

****>/path/to/logfile

#Append to log each time it's run, but still send mail

@reboot/script.sh>>/reboot.log

Crontab Mail Silence

Shell

1

2

#Still sends to syslog, but not a mail.

****>/dev/null2>&1

/dev/null logging will also prevent weird script output that might terminate the crontab

Crontab Log and Silence Mail

It is a good idea to capture so syslog picks up errors (2>&1)

Shell

1

****>/path/to/logfile2>&1

Crontab Mail

Sometimes when logging in you’ll see something like “You have new mail.” These could be crontab messages.

If there is no output from cron, there will be no mail. By default mail goes to the same user as the crontab, but can be forced to a different user by adding the following command at the top of the crontab -e session:

Shell

1

2

MAILTO=user@somehost

MAILTO=user

If you wish to change default mail to root instead edit your /etc/default/cron:

Shell

1

MAILTO=root

This file contains cron’s default settings.

How to Read Local Mail in Linux

This mail is stored in a text file per user in /var/mail/ or /var/spool/mail/

You can easily read the mail by simply catting the file:

Shell

1

cat/var/spool/mail/root|more

It can be read using one of the following programs if you wish to properly read the email:

alpine

mutt

mail/mailx

Configure the “MTA” aka /usr/sbin/sendmail to send to external mail as well so you can read it in your favorite external reader. Be advised that many of these messages could contain sensitive info.

Edit /etc/aliases

By default mail goes to a user on the system. Users can be listed in the /etc/passwd file.