How To Send Email Notification Upon Success or Failure of Bash Script

In this guide we are going to look at some questions asked by our readers, which is related to handling errors notifications during the execution of shell script.

A good shell script must have ability to notify the situation if something goes wrong.


Get Email Notification in case a Bash Scrip is failed or successful

LAB Requirements

  • CentOS 7.x / Red Hat Enterprise Linux 7.x
  • Valid Gmail Account

Installation of Required Softwares:

We are installing Postfix as MTA (Mail Transfer Agent) and mailx (which is command line email sending program) so that we can send email notification using bash script.

# yum  install postfix  mailx cyrus-sasl-plain cyrus-sasl -y

Postfix Configuration

Configure Postfix by adding below lines at the end of /etc/postfix/ file.

# vi /etc/postfix/

Add below lines at the end of file.

relayhost = []:587
smtp_sasl_auth_enable = yes
smtp_use_tls = yes
smtp_tls_CAfile = /etc/ssl/certs/ca-bundle.crt
smtp_sasl_security_options = noanonymous
smtp_sasl_tls_security_options = noanonymous
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd

Simply Save & Exit.

Configure Postfix SASL Credentials for gmail as relay host.

Create a file named /etc/postfix/sasl_passwd and add below line. The username and password values must be replaced with valid gmail account.

# vi /etc/postfix/sasl_passwd
# []:587 username:password

Save & Exit.

Generate Postfix lookup table from sasl_passwd file by running below command.

# postmap /etc/postfix/sasl_passwd

Make sure the Gmail credential file is accessible only by root.

# chown root:postfix /etc/postfix/sasl_passwd
# chmod 640 /etc/postfix/sasl_passwd

Enable Postfix on startup

# systemctl enable postfix

Finally, start the Postfix service.

# systemctl start postfix

Enable “Less Secure App“

Default setting of Gmail allows only the most secure sign-ins, e.g logging in to Gmail through web browser. To permit relay requests log in to your Gmail account, “Allow less secure apps option must be turn on.

Login to you Gmail account using web browser and then click on This Link to directly reach “Less Secure App” settings page.

If you have followed above steps properly, so you have now working Postfix server which can send email using external Gmail SMTP server.

Email Notification Using Bash Script

At this point we are ready to modify our shell script to send email notification using mailx command.

To examine the success or failure notification of a program we need to understand what is exit status in Linux command line.

In Linux shell “$?” environment variable will contain the exit status of the last command executed.

Lets suppose you have one directory called “/mybackupfolder” and you enter in this directory using change directory command.

# cd /mybackupfolder

Using ‘$?’ environment variable we can see what is the exit status of previous command. If the exit status is 0 so its mean previous command was run successfully and if its not zero, so its showing our command was not successful.

# echo $?

Now we will delete “/mybackupfolder” directory and execute same change directory command.

# rm -fr /mybackupfolder/
# cd /mybackupfolder -bash: cd: /mybackupfolder: No such file or directory

Now shell is showing error message “No such file or directory” which means we are trying to enter a directory which is not there anymore, now lets examine exit status of this command.

# echo $? 1

After understanding command exit status, now we can implement same concept in our bash script to trigger email and send success or failure status by examining zero or one.

Below is our old backup script with additional email sending feature.

#Purpose = Backup of Important Data
#Created on 17-1-2012
#Updated on 21-05-2016
#Author = Hafiz Haider
#Version 2.0
TIME=`date +{1c918b003a0fec779e46518dd4d8df22f3dc554de918030f5a1a0cfd93cb28be}b-{1c918b003a0fec779e46518dd4d8df22f3dc554de918030f5a1a0cfd93cb28be}d-{1c918b003a0fec779e46518dd4d8df22f3dc554de918030f5a1a0cfd93cb28be}y`            # This Command will add date in Backup File Name.
FILENAME=backup-$TIME.tar.gz    # Here i define Backup file name format.
SRCDIR=/imp-data                    # Location of Important Data Directory (Source of backup).
DESDIR=/mybackupfolder            # Destination of backup file.
#Email Notification
if [ "$?" = "0" ]; then
        echo "Backup Process was Successful. A new backup file $FILENAME has been created" | mailx -s "Backup Status Successful"
         echo "Backup Process Failed. Please contact System Administrator" | mailx -s "Backup Status Failed"
        exit 1

Script Explanation:

In this version, we examine the exit status of the tar command and if it’s zero a success message will send by email or if its not zero, script will trigger an email with error message and terminate the script with an exit status of 1.

You can execute script and get email notification on your specified email address in script.

That’s All… Let me know if it works for you if you have any suggestion please fill in comment box, i read your comments daily !!

Thanks :).

Similar Posts