4

As per the monitoring of my mysql replication status. I wrote a simple shell script with the following code

#!/bin/bash
date > /tmp/mysql_repl_status.txt
cd /usr/bin/
"/usr/bin/mysql" "-e" "SHOW SLAVE STATUS \G" >> /tmp/mysql_repl_status.txt
mail -s "Netspective MySQL replication status" name@abc.com < /tmp/mysql_repl_status.txt

The issue is when i execute this script manually it works fine, but using cron the script not works.

Using cron got the mail with the output of date command only. What is wrong with my side?

polym
  • 10,852

4 Answers4

4

Several possibilities:

  1. Cron doesn't pass a full user environment to scripts run under cron. So vars like $PATH can be different running under cron than running in a user terminal.

  2. Cron requires a newline at the end of every line, so always keep a blank line at the end of the crontab file.


Maybe specify the full paths in the script, and see if that works to start with.

#!/bin/bash
statfile=/tmp/mysql_repl_status.txt
/bin/date > $statfile
cd /usr/bin
/usr/bin/mysql -e "SHOW SLAVE STATUS \G" >> $statfile
/bin/mail -s "Netspective MySQL Replication Status" name@abc.com < $statfile
Tim Kennedy
  • 19,697
  • 1
    Quoting the path to a command (point 3) is not an issue. It's how you run a command with spaces or other special characters (which should never happen in a sensible system, but you know). – l0b0 Jun 19 '14 at 13:53
  • I would also add 2>&1 to the end of the mysql command line to pick up any error messages. – doneal24 Jun 19 '14 at 18:57
  • @DougO'Neal It would be better to configure mail properly so that cron's email doesn't get lost. If a cron job emits anything on stdout or stderr, cron sends the output in an email. – Gilles 'SO- stop being evil' Jun 19 '14 at 22:06
  • The script is executed under bash, not under a “reduced shell”. And anyway cd /usr/bin is supported by all shells. – Gilles 'SO- stop being evil' Jun 19 '14 at 22:08
  • Sorry. I meant to say a reduced environment. Cron often doesn't run script with the same environment a user would get in an interactive shell. – Tim Kennedy Jun 20 '14 at 01:27
2

Cron jobs are run with very little context. If you have a .my.cnf file in your home directory, that could contain the authentication details needed for the mysql command to work. You probably also need the full path to mail - see what which mail prints.

l0b0
  • 51,350
1

Instead of writing full path for every command, it would be helpful to set PATH variable in the script file itself

#!/bin/bash
export PATH=/usr/local/sbin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
date > /tmp/mysql_repl_status.txt
cd /usr/bin/
"/usr/bin/mysql" "-e" "SHOW SLAVE STATUS \G" >> /tmp/mysql_repl_status.txt
mail -s "Netspective MySQL replication status" name@abc.com < 
/tmp/mysql_repl_status.txt`
Sourav
  • 1,343
0

use bash -l -c

eg:

* * * * * bash -l -c '/dsds/fddfd/something.sh' > /tmp/something.log
muru
  • 72,889