Bash ScriptMySQL

How-To: Create a Cron Job to start MySQL if it Stops

Sometimes server acts weird and stops some services due to any issue

Creating Shell Script

Step 1: Open Terminal and login to your server as root via ssh.

Step 2: Create shell script file.

cd ~
nano mysqlfix.sh
chmod 755 mysqlfix.sh

Step 3: Write the script to check and restart MySQL

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

Step 4 : Create the cron job

crontab -e

Once you see the crontab screen type the following line at the end of this file:

*/1 * * * * /root/mysqlfix.sh

Testing the script

Now our script is ready, let’s test if this runs fine.

Enter following commands in the terminal:

/usr/sbin/service mysql status

The terminal will print something like this:
mysql start/running, process 2409

/usr/sbin/service mysql stop

This will stop MySQL service, to verify run the status command again and it will print something like this:
mysql stop/waiting

~/mysqlfix.sh

This will run the script we created to check and restart the service.