MAILTO

Now that we've determined we can use environment variables in our crontab by checking out both PATH and SHELL, let's look at the other very important one, MAILTO. As you might guess from the name, this variable controls where mails will be sent. As you remember, mails are sent when a command has stdout (which are pretty much all commands). That means that for every command the crontab executes, you'll probably get a local email. This, as you might suspect, can become annoying very quickly. We could suffix a nice little &> /dev/null to all commands we place in the crontab (remember, &> is Bash-specific, and would not have worked for the default Dash shell). However, this would mean that we never have any output at all, mailed or otherwise. Besides that problem, we'll also need to add it to all our lines; not really a real practical, workable solution. In a few pages, we're going to discuss how we can redirect our output to somewhere we want. Before we get to that point, however, we need to be able to manipulate the default emails as well.

One option would be to either not install or uninstall sendmail. This might be a good solution for some of you, but for others there is another need to have sendmail on the system, so it cannot be removed. What then? We can use the MAILTO variable in the same way as we use the PATH; we set it in the beginning of the crontab, and mails will be properly redirected. If we empty this variable, by assigning it the empty string "", no mail will be sent. This looks something like this:

reader@ubuntu:~$ crontab -e
no crontab for reader - using an empty one
crontab: installing new crontab
reader@ubuntu:~$ crontab -l
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
MAILTO=""
# m h dom mon dow command
* * * * * echo "So, I guess we'll never see this :("

We've used the tail command a lot up until now, but it actually has a great little flag --follow (-f), which allows us to see if any new lines are being written to a file. This is normally used to tail a logfile, but in this case allows us to see whether we get mail by tailing the /var/mail/reader file:

reader@ubuntu:~$ tail -f /var/mail/reader 
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/home/reader>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=reader>

/bin/bash: 1: blkid: not found

If everything went as we expected it to, this is the only thing you will see. Since the MAILTO variable was declared as the empty string, "", cron knows not to send out mails. Exit the tail -f with Ctrl + C (but remember the command), and rest easy now that you've prevented yourself from being spammed by your crontab!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.236.27