
Update Your Clock via the Internet #71
Chapter 9, Administration and Automation
|
219
HACK
Make cron Email You
To cement your knowledge of cron let’s try creating a cronjob that does
something dynamic. The following cronjob emails you a daily report show-
ing the current disk usage on your computer:
0 0 * * * echo -e "This is a summary of disk usage on your
server:\n\n `df -h`" | mail -s 'Disk report for `hostname`
on `date`' foo@bar.org
In this example, use the echo command to create the text of the email; then
embed the
df (disk free) command in backticks and pipe the output to the
mail command. Then the command creates the subject line of the email
dynamically by calling the
date and hostname commands.
This example illustrates that you can perform quite complex tasks as cron-
jobs, but that the crontab file itself can start to look very confusing. If you
intend to do more complex tasks, such as the one in the previous example,
it’s probably better to put the code that does the actual work into a separate
script file, and then just call it from the crontab. For safety it’s also consid-
ered good practice to have your cron entry test that the script it is trying to
call actually exists and can be executed. For the previous example, you can
create a script called /home/foo/diskreport.sh like this:
#!/bin/sh
echo -e "This is a summary of disk usage on your
server:\n\n `df -h`" | mail -s 'Disk report for `hostname` ...