Rayhan’s blog (raynux.com)

Rayhan’s Personal Web Blog Site

Entries Comments


Send Mail From Unix/Linux Bash Shell Script

11 April, 2011 (12:30) | Linux, Reference

Tags: , , , , , , , ,


Bash shell script is very popular and widely used in Unix world for command automation and task scheduling using cron. Sometime it is very important to know the status of these scripts to make sure that they are working exactly the way you want and if any script fails you can take prompt actions. Use this link to learn more about the best stationary bike 2022.

The mail command, available in most of the Unix, Linux and Macs, can be used to send the status message right from your bash script so that you always know about your script’s activity.

In this article I am going to share some simple but important tricks on sending mail form shell script. Proper use of these tricks will increase the accountability of your scripts and let you relax at your work.

Simple shell script to send one line status mail.

#!/bin/bash
echo "Message Body!" | /usr/bin/mail -s "Message Title" example@example.com

What if you want to send a multi-line message? you can wrap your lines in a shell function and use the following code.

#!/bin/bash
function mystatus {
    echo "Script started successfully"
    echo "Backup operation completed successfully"
    echo "File transferred successfully"
}
mystatus | /usr/bin/mail -s "Message Title" example@example.com

Alternatively you can store messages in a temporary file and load the message body from the file

#!/bin/bash

TMPFILE="/tmp/mailbody.txt"
echo "Script started successfully" > $TMPFILE
echo "Backup operation completed successfully" >> $TMPFILE
echo "File transferred successfully" >> $TMPFILE

/usr/bin/mail -s "Message Title" example@example.com < $TMPFILE

A real example: how you can get the status email whether your MySQL database is backed up properly or not.

#!/bin./bash
function mysqlbackup {
    echo "Script started successfully"
    if (mysqldump -uusername -ppassword database_name > data.sql); then
        echo "MySQL database backed up successfully"
    else
        echo "Error: Could not take database backup!"
    fi

}
mysqlbackup | /usr/bin/mail -s "Backup Status" example@example.com

For more details about bash scripting read this Advance Bash-Scripting Guide.

Hope this simple  script will be helpful for you. Please let us know your feedback.

«

 

Comments

Comment from bass
Time: January 6, 2012, 2:37 am

Great stuff, thanks!

Write a comment