Shell script issue: cron job script to Restart MySQL server when it stops accidentally

I suspect that you setup the cron job to execute this script in your crontab file, and not in the root crontab file. This is not correct because if you don't run service mysql status as root, the mysql service will not be recognized.

So, modify the script as follow:

#!/bin/bash
if [[ ! "$(/usr/sbin/service mysql status)" =~ "start/running" ]]
then
    /usr/sbin/service mysql start
fi

Be sure that is executable:

chmod +x /path/to/script

Then add a new entry in the root crontab as follow:

  • Edit root crontab file using:

    sudo crontab -e
    
  • And add the following line to the file:

    */1 * * * * /path/to/script
    
  • Note: I have set the cron job for every minute, but you can change as you wish or as you think is better. See http://en.wikipedia.org/wiki/Cron in this sense.


Radu's answer nearly worked. I had to set the path to make it work:

#!/bin/bash
PATH=/usr/sbin:/usr/bin:/sbin:/bin
if [[ ! "$(service mysql status)" =~ "start/running" ]]
then
    service mysql start
fi

Radu's answer works - but this script works as well

#!/bin/bash
if [[ $(pgrep mysql | wc -l) = 0 ]];
then
    sudo service mysql start;
fi