Mailing from a Script

You may want to be informed of the progress or success of a script. One way to achieve this is to use the mail command in the script. It will resemble the following:

echo "many happy returns" | mail -s "Happy Birthday" [email protected]

This sends an e-mail with the subject Happy Birthday and the content "many happy returns'' to the address given. Note that the message body could have been obtained from a file on the system. Of course it's more likely that the kind of message being sent is something like "Backup complete,'' but there are almost certainly system administrators out there who use a cron job and a mail script to avoid the risk of forgetting their spouse's birthdays!

A more sophisticated way of using a block of text within a script is the so-called here-document. Within a script, the symbol << together with a string that defines the end of the block is used to define the block of text that is to be redirected to a command. Very often the string EOF is used as the limit string.

For example:

Happy birthday to you Happy birthday to you EOF

If you run this, you will see the following:

Happy birthday to you Happy birthday to you

To mail the greeting, do the following: #! /bin/bash mail -s "Birthday Greetings" [email protected]<<EOF Happy birthday to you Happy birthday to you EOF

Was this article helpful?

0 0

Post a comment