Your code will not work at all, this is a modified version:
#!/bin/bash # ping checker tool FAILS=0 EMAIL_ADDRESS=" example@example.com " SERVER="192.168.1.1" SLEEP=60 while true; do ping -c 1 $SERVER >/dev/null 2>&1 if [ $? -ne 0 ] ; then #if ping exits nonzero... FAILS=$[FAILS + 1] else FAILS=0 fi if [ $FAILS -gt 4 ]; then FAILS=0 echo "Server $SERVER is offline!" \ | mail -s "Server offline" "$EMAIL_ADDRESS" fi sleep $SLEEP #check again in SLEEP seconds done
Change example@example.com and 192.168.1.1 for your email address and the IP address of the server you are testing. I recommend using an IP address instead of a host name to prevent confusion of name resolution errors with connection errors.
Please keep in mind that although this will work, I would recommend running a slightly different script from cron instead of working continuously, as you think, when you start with cron you wonβt need to keep track of what the script is running, because, if it stops for some reason, server monitoring also stops.
Something like this starts from crontab every minute.
#!/bin/bash # ping checker tool TMP_FILE="/tmp/ping_checker_tool.tmp" if [ -r $TMP_FILE ]; then FAILS=`cat $TMP_FILE` else FAILS=0 fi EMAIL_ADDRESS=" example@example.com " SERVER="192.168.1.1" ping -c 1 $SERVER >/dev/null 2>&1 if [ $? -ne 0 ] ; then #if ping exits nonzero... FAILS=$[FAILS + 1] else FAILS=0 fi if [ $FAILS -gt 4 ]; then FAILS=0 echo "Server $SERVER is offline!" \ | mail -s "Server offline" "$EMAIL_ADDRESS" fi echo $FAILS > $TMP_FILE
source share