Here is the simple shell script check the MySQL service status, if MySQL service is not running then start MySQL service.

#!/bin/bash

SERVICE='mysql'
if ps ax | grep -v grep | grep $SERVICE > /dev/null
then
   echo "$SERVICE service is running."
else
   echo "$SERVICE is not running"
   service mysqld start
fi

Let me describe about the command we use here. Specially why we are using grep -v grep.

grep -v :

When you want to display the lines which does not matches the given string/pattern, use the option -v as shown below

grep -v grep:

This option will exclude all “grep” command from running process list.

grep -v grep” help here to exclude “grep mysql” from console. If mysql services is stopped and someone runs “ps ax | grep mysql” then command “ps ax | grep mysql” will fail here.

Example Output :

$  ps ax | grep mysql
------------------------
3456 pts/1    S      0:00 /bin/sh /usr/bin/mysqld_safe --datadir=/var/lib/mysql --socket=/var/lib/mysql/mysql.sock --pid-file=/var/run/mysqld/mysqld.pid --basedir=/usr --user=mysql

5634 pts/1    Sl     0:01 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --user=mysql --log-error=/var/log/mysqld.log --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/lib/mysql/mysql.sock

6433 pts/1    S+     0:00 grep mysql

 
 $ ps ax | grep -v grep | grep mysql

4395 pts/1    S      0:00 /bin/sh /usr/bin/mysqld_safe --datadir=/var/lib/mysql --socket=/var/lib/mysql/mysql.sock --pid-file=/var/run/mysqld/mysqld.pid --basedir=/usr --user=mysql
 
 4497 pts/1    Sl     0:01 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --user=mysql --log-error=/var/log/mysqld.log --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/lib/mysql/mysql.sock

“>/dev/null”  in  ‘if’  statement

if” doesn’t need output of the grep. It only require some lines matching the condition but not the output of the grep command. So I have redirected grep output to /dev/null.

Few more Linux reference :

https://github.com/roopendra/devops/tree/master/bash_scripting

(Visited 95 times, 3 visits today)