Cronjob fails then Get alerts by email | Bash Script
by Prashant · Published · Updated

OVERVIEW
In this guide, I am going to share a bash script that helps you to set an email alert for the Cronjob fails. This script will keep alerting you when your cronjob fails because of any issues on the server.
Condition Use In Script:
Check for the Status code ‘200’ if status code, not 200 then send email alert for cronjob fails.
This is a comprehensive automated script that will send you an email notification when the above conditions are true.
Make sure you have a mail server configured on your server. if not then follow the below link which helps you to configure a mail server.
Read: STEPS TO INSTALL POSTFIX SERVER ON LINUX
vim CronChecker.sh
#!/bin/bash
###########################################
# Title : CronChecker.sh #
# Version : 1.0v #
# Usage : ./CronChecker.sh #
###########################################
# Variables
CRONFILES="[email protected]"
MAIL=$(which mail)
WGET=$(which wget)
MAILTO='[email protected]'
CRONURL="$1"
CRONLOGFILE="$2"
# Check for Cron URL and Logfile.
if [ -z "${CRONFILES}" ]; then
echo -e "Please provide Cron URL and Log File path.nUsage: $0 ......"
exit 1
fi
# Execute the Cron
$WGET -O - $CRONURL > $CRONLOGFILE 2>&1
# Check for Logfile.
if [[ -s "${CRONLOGFILE}" ]];
then
STATUSCODE=$(cat $CRONLOGFILE | grep 'HTTP request sent'| sed 's/[^0-9]//g' | head -n1)
BODY="nnFor more information please check $CRONLOGFILE.nnnThanks,n$0"
if [ "$STATUSCODE" -ne 200 ];
then
echo $STATUSCODE
echo -e "Hi SysAdmin, nnThe Cron execution gives error $STATUSCODE on CronURLnn" $BODY | $MAIL -s "Cron Error in $CRONURL" $MAILTO
fi
else
echo -e "Cron Log File is empty"
exit 1
fi
Check Script File Permission
Once you save the script, provide executable permission to run the script.
$ chmod +x CronLogChecker.sh
Use the script with the Cron
Now you need to use this script file with the cron url. Use this script as per the below instructions.
$ crontab -l
30 1 * * * root /bin/bash /opt/CronChecker.sh http://your-cron-url /tmp/cron-url-log.tmp
Save and close the file.
This is a well-tested script and provides you data without using more memory on the server.
You can modify the above script according to your requirement. If you still face any issues to setup this script then comments down below in comment box.
Stay connected & subscribe with linuxgrow.com for more such articles.