MySQL process check with cron

I can run this script fine from the terminal and I get the else but when I have cron set to run it every 5 minutes I am sent a email and the mysql server is restarted every 5 minutes. So I am guessing that the cron job does not have the correct permission to see if the process is running, so it restarts the server and sends an email. How would I get this script to execute from cron and be able to check if mysql process is running?

UP=$(service mysql status | grep 'mysql start/running' | wc -l);
if [ "$UP" -ne 1 ];
        sudo service mysql start
        cat /var/db-backup/mysql_restart_email | msmtp
        echo "All is well.";


ok so dumped the variable $up to a text file.

dead.letter /usr/bin/mysqladmin Ver 8.42 Distrib 5.5.43, for debian-linux-gnu on x86_64 Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Server version 5.5.43-0ubuntu0.14.04.1 Protocol version 10 Connection Localhost via UNIX socket UNIX socket /var/run/mysqld/mysqld.sock Uptime: 2 min 29 sec Threads: 2 Questions: 2232 Slow queries: 0 Opens: 633 Flush tables: 1 Open tables: 400 Queries per second avg: 14.979

Why would I be getting that instead of ?

mysql start/running

I do have a swap file and It does not crash that often maybe once a month, but I have a client that is annoying and cheap and if it does hes contacting me left and right.

Yes it was added while logged in as root

I should also note that if your MySQL process is crashing regularly that you should consider taking other measures as this will eventually result in your data being corrupted and the service possibly not being able to start at all. The most common reason for MySQL to be crashing is running out of memory. Creating a swap file can provide a useful stopgap against this occurring but for the best performance you may want to consider upgrading to a larger droplet.

It works great when I execute it from the terminal with ./

When mysql is stopped: mysql stop/waiting

When mysql is running: mysql start/running, process 2554

When you added your script to your crontab did you do a crontab -e as the root user? If you did then the script should be running with root privileges and permissions would not be the issue.

This comment has been deleted

Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

when you set up the cronjob, are you running:

sudo crontab -e

Here is my take on the same idea, but I made it so the script checks on other services (like Apache2)

works fine on all my DO droplets for the last several months.