0

I have a simple bash script scheduled to run every 10 minutes, which checks for the PID of any service, and if it is not found, it sends an email alert:

#!/bin/bash
if pgrep "mysql" > /dev/null
then
    echo "MYSQL Running"
else
    echo "ALERT Stopped"
    # Sends Email Alert blah blah
fi

The issue is that if somehow the required service is down permanently, it keeps sending emails every 10 minutes. How can I set up a check so that if the service is down and an email sent once, then no emails should be sent until the service comes up again. Then, if the service is subsequently down again, a new email should be sent.

2

Try something like this:

#!/bin/bash
if pgrep "mysql" > /dev/null
then
    echo "MYSQL Running"
    rm -f /var/run/.mysql_mail_sent
else
    echo "ALERT Stopped"
    if [ ! -f /var/run/.mysql_mail_sent ]; then
        // send your mail here
        date > /var/run/.mysql_mail_sent
    fi
fi
  • I don't like that it's storing a dotfile in root. This might be more sensible somewhere in /var/run perhaps? Also, just having looked through that again, I think you might slightly have the wrong end of the stick - we want to remove the file when mysql starts running again, and put the file in place when it's stopped, not the other way around? – Muzer Jul 24 '15 at 9:54
  • 2
    It's just an example. You can store such file in /var/run, /tmp etc. – Tomasz Klim Jul 24 '15 at 9:56
  • You are free to put the file wherever you want. It is just a proposal. For my scripts I use a special directory for logfiles and these kind of dot files (but I call them with a .lck extension). Also you can create this file in the else part and change the startup of mysql to remove the file if you want. – Marco Jul 24 '15 at 10:00
  • I want to send email ONLY if the service is down and the email should be sent once only (until the service gets up) Seeing your script, I can see its sending email in both conditions? can you please explain a bit? – Syed Jahanzaib Jul 24 '15 at 10:24
  • It was only an example of bash language elements required to write your desired logic, not the finished script - because I wasn't sure about its exact behaviour you want to achieve. – Tomasz Klim Jul 24 '15 at 10:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.