Thursday, May 2, 2024
 Popular · Latest · Hot · Upcoming
20
rated 0 times [  20] [ 0]  / answers: 1 / hits: 39243  / 1 Year ago, tue, december 13, 2022, 2:34:13

I have this script, I am using it to setup CRON job to execute this script, so it can check if MySQL service is running; if not then it restart the MySQL service:



#!/bin/bash
service mysql status| grep 'mysql start/running' > /dev/null 2>&1
if [ $? != 0 ]
then
sudo service mysql restart
fi


I have setup cron job as.



sudo crontab -e


and then added,



*/1 * * * * /home/ubuntu/mysql-check.sh


Problem is that it restart MySQL on every cron job execution..
even if server is running it restart the MySQL service
what is correction in the script to do that.


More From » bash

 Answers
1

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.



[#25837] Tuesday, December 13, 2022, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
odyroc

Total Points: 324
Total Questions: 109
Total Answers: 103

Location: Belize
Member since Mon, Apr 17, 2023
1 Year ago
odyroc questions
;