1

I have written a shell script to start mysql server & send a mail to admin user if it's restarted via shell script. What i am facing an issue if I run this shell script on terminal it's work perfectly & If same script runs via cronjob it's only sending the mail to the user & problem remains same. Is this problem relates to permission & how can i resolve it.

Shell Script--------

#!/bin/bash
EMAIL="abc@xyz.com"
SERVICE='mysql'
if ps ax | grep -v grep | grep $SERVICE > /dev/null
then
   echo "$SERVICE service running, everything is fine"
else
   echo "$SERVICE is not running"
   /etc/init.d/mysql start
cat <<EOF | msmtp -a gmail $EMAIL
Subject: "Alert (Test Server) : Mysql Service is not running (Manually Restarted)"
Mysql Server Restarted at: `date`
EOF
EXIT

I am using msmtp for sending mail to the user on ubuntu 12.04 Server.

John Gardeniers
  • 27,458
  • 12
  • 55
  • 109
user103373
  • 198
  • 6
  • 19
  • Why bother? This is exactly what monit was designed to do – Ben Lessani Sep 19 '12 at 08:12
  • Why bother installing and configuring monit when all that's required is a simple script? – John Gardeniers Sep 19 '12 at 11:40
  • 1
    just curious, is that the full script ?, where is the end of if block (fi) after EXIT ? (please ignore if it's typo). have you try to log the output of /etc/init.d/mysql start ?, try add /etc/init.d/mysql start 2>&1 | tee -a /tmp/mysql.log you can see the output/error on /tmp/mysql.log – chocripple Sep 19 '12 at 13:55
  • Hi Rikh, this is the ouput of log (Since the script you are attempting to invoke has been converted to an Upstart job, you may also use the start(8) utility, e.g. start mysql /etc/init.d/mysql: 73: start: not found ) – user103373 Sep 20 '12 at 06:04

2 Answers2

0

Just a though, but you might want to look at something like monit. It is specifically designed just for this purpose.

In any case, how have you setup the cronjob? Did you create a file in /etc/cron.d/ did you create it using crontab -e using your normal user account or what? I am tempted to guess you setup your cronjob as a user without enough privileges.

Zoredache
  • 130,897
  • 41
  • 276
  • 420
  • I am using crontab -e to run this script using root user account. which runs at every 5 min, */5 * * * * /bin/sh /root/script/service.sh – user103373 Sep 19 '12 at 06:20
0

It seems to be an environnement issue, use complete path for binary like msmtp should resolve your problem.

Your script has same role than /usr/bin/mysqld_safe, maybe it's better for you to hack mysqld_safe to send you an email.

profy
  • 1,146
  • 9
  • 20