Restart mySQL if server load is more then 10

I am trying to write a shell script which I will later put in cron for checking server load and if server load is more then 10, it will restart mySQL.

Presently if I comment line number 7, I do get the email alert but command for mysql restart is not working. This command does work for me on SSH for restarting mysql.

Please help.

#!/bin/bash
srvrnm=`hostname` # get the hostname of the server 
MRESTART="/sbin/service mysqld restart"
temp="/home/admin/script/tmp/mailinfo" # File storing formated output 
cur=`uptime | awk '{print $10}' | tr -d , | cut -d. -f1` # Load avg 
if [ $cur -ge 10 ]; then # Condition if 
$MRESTART>/dev/null
################### Formation for email output ##################
echo "Hi," > $temp 
echo " " >> $temp 
echo " " >> $temp 
echo "We have noticed high server load on `hostname`." >> $temp 
echo " " >> $temp 
echo " " >> $temp 
echo "Thanks," >> $temp 
echo " " >> $temp 
echo "- Linux SysAdmin." >> $temp 
###################################################### 
mail -s "Alert: Server Load `hostname`" mailme@yahoo.com < $temp 
fi

Open in new window

LVL 1
tripatAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
sentnerConnect With a Mentor Commented:
Try removing the ">/dev/null" and do a test run of the script from the command line (not cron), using:
bash -x [scriptname]

This will tell what's executing.  Paste the output back here.
0
 
ravenplConnect With a Mentor Commented:
Can You try without variable, but literal command?

Also, personally use: /etc/init.d/mysql restart > /dev/null

Also, the mail sending can be tuned not to use temp file as follows

echo << EOF | mail -s "Alert: Server Load `hostname`" mailme@yahoo.com
Hi,

We have noticed high server load on `hostname`.

Bla bla
EOF
0
 
ahoffmannConnect With a Mentor Commented:
I'd not use ..../mysql restart  except you're 101% sure that it exactly does what you want/need (some script just send a -HUP signal for example)
Use something like:
/etc/init.d/mysql stop && /etc/init.d/mysql start && mail -s"restart successful" you@some.where
0
 
tripatAuthor Commented:
Thanks for your help, I found out that I was running this script as user not having root permissions so the command of mysql restart was not working.

when I run this as root, it works fine.
0
All Courses

From novice to tech pro — start learning today.