Mailing from scripts

The scripts you write will often be rummaging around your system at night when you’re asleep or at least while you’re not watching. Since you’re too busy to check on every script’s progress, a script will sometimes need to send some mail to you or another administrator. This is particularly important when something big goes wrong or when something important depends on the script’s outcome. Sending mail is as simple as piping into the mail command:

echo "Backup failure 5" | mail -s "Backup failed" root

The -s option indicates that a quoted subject for the email follows. The recipient could be yourself, root, or if your system is configured correctly, any Internet email address. If you need to send a logfile, redirect the input of mail from that file:

mail -s "subject" recipient < log_file

or:

cat log_file | mail -s "subject" recipient

Sending email from scripts is easy and makes tracking status easier than reviewing logfiles every day. On the downside, having an inbox full of “success” messages can be a nuisance too, so many scripts are written so that mail is sent only in response to an important event, such as a fatal error.

Get LPI Linux Certification in a Nutshell, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.