Edit your cron to add alerts

If you’re using CRON to run jobs, there’s an easier way to integrate alerts into your setup.

You can use this sendalert.sh script to send an email which will then trigger an alert.


#!/bin/bash

if [ -z "$1" ] || [ -z "$2" ] ;
then
    echo "Email address is required as the first parameter"
    echo "and the alert message as the second parameter"
    echo "E.g. /bin/bash "$(basename $BASH_SOURCE)" [email protected] \"This is the alert message\""
fi

SENDMAIL=$(which sendmail)
MAIL=$(which mail)

if [ "$SENDMAIL" != "" ];
then

    echo "Subject: $2" | sendmail $1

elif [ "$MAIL" != "" ];
then

    mail -s "$2" $1 < /dev/null
    
else

    echo "Could not find sendmail or mail program"

fi

E.g. here is a job which runs at midnight

0 0 * * * /bin/bash runbatchjob.sh

By adding to the end of this command, we can trigger alerts without modifying any of the code inside the runbatchjob.sh script.

0 0 * * * /bin/bash runbatchjob.sh || /bin/bash sendalert.sh [email protected] "This is the alert message"

What this command will now do is run the batch job script and only if it fails will it trigger an alert.

The sendalert.sh script will try to use sendmail at first and if it is not available it will try the mail program. Remember to run chmod +x sendalert.sh to make it executable.

You can also use the direct approach if you wish.

E.g. using sendmail

0 0 * * * /bin/bash runbatchjob.sh || echo "Subject: This is the alert message" | sendmail [email protected]

Or via mail.

0 0 * * * /bin/bash runbatchjob.sh || mail -s "This is the alert message" [email protected] < /dev/null