Tutorial

How To Write a Bash Script To Restart Server Programs

Published on August 30, 2012
How To Write a Bash Script To Restart Server Programs

To ensure that the most imperative programs remain online as much as possible (even after a server crash or reboot), one can create a short bash script to check if the program is running, and if it is not, to launch it. By using cron to schedule the script to be executed on a regular basis, we can make sure that program relaunches whenever it goes down.

Bash Script

The first step in this process is to create the script itself. There are a variety of programs such as upstart, supervisor, and monit, that have the capability to start and monitor applications on a virtual private server in a very nuanced way— this bash script will simply provide an on switch.

Below is a sample script that starts apache if it finds it off.

nano launch.sh
#!/bin/sh

ps auxw | grep apache2 | grep -v grep > /dev/null

if [ $? != 0 ]
then
        /etc/init.d/apache2 start > /dev/null
fi

Once you have saved the script, you must give it executable permissions in order to be able to run it:

chmod +x launch.sh

Apache can be replaced with any required application. Should you want to set up the script for a variety of applications, you can create a new script for each one, placing it on its own line in the cron file.

Cron Setup

With the script in hand, we need to set up the schedule on which it will run. The cron utility allows us to schedule at what intervals the script should execute. Start by opening up the cron file:

crontab -e

Cron has a detailed explanation of how the timing system works at the beginning.

Once you know how often you want the script to run, you can write in the corresponding line.

The most often that the script can run in cron is every minute. Should you want to set up such a small increment, you can use this template:

* * * * * ~/launch.sh

Every five minutes would be set up like this:

*/5 * * * * ~/launch.sh

See More

Setting up this simple script will keep the program starting up after it shuts down for any reason. This is convenient as it will ensure that the longest time that a program will be down is for the interval of time that you specified in the cron configuration.

Should you need a program that is even slightly more subtle, you can set up the details of your startup with one of the several server monitoring programs (Supervisor, Upstart, or Monit).

By Etel Sverdlov

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
10 Comments


This textbox defaults to using Markdown to format your answer.

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

Don’t you need to make sure that the script is executable by doing something like u+x ~/launch.sh?

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
October 21, 2013

@Marc: That is correct, I’ve updated the article. Thanks!

I’m using this script to restart mysql with no luck. Log says

/root/mysql-check.sh: 2: [: unexpected operator
Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
July 13, 2014

@robert: Can you pastebin the contents of /root/mysql-check.sh?

I’m trying to utilise this script and crontab to keep an eye on MySQL.

I couldn’t get the script to work.

#!/bin/sh

ps auxw | grep mysql | grep -v grep > /dev/null

if [ $? != 0 ]
then
        service mysql restart > /dev/null
fi

I’m very inexperienced with this stuff but reviewing the above shouldn’t it be:

if [ $? = 0 ]

I’m not really sure the significance of the $? in the above though I would assume it’s a print of the output from the previous command.

I’m probably wrong here but if MySQL is down and thus not printed in ps auxw and we’re removing the grep process too then isn’t an output of nothing what should be triggering the process restart?

EDIT: No that still doesn’t solve the problem. If I use = 0 the service reboots at every run of the script. If I use != 0 then the service never reboots. Confused.

Anyone able to help on this?

Thanks for the tutorial of how to make a bash script. However for this case I would prefer something like “service apache2 status || service apache2 start” directly on the crontab line. I saw that trick here https://www.digitalocean.com/community/questions/how-do-you-check-mysql-status-via-cron?answer=18288

hello i add the commande and when i try to add cron tab i got this ? */1 * * * * ~/launch.sh -bash: */1: No such file or directory

Sorry but it does not work… It doesn’t restart my programs…

Some problem here too.

My script works just fine. It is in /etc/apache2/relaunch.sh, file permissions are

-rwxr-xr-x   1 root root   372 Feb 21 08:01 relaunch.sh*

here’s the script

#!/bin/sh
echo "running apache2 relaunch at $(date)" >> /var/log/uwe-crontab/crons.log
ps auxw | grep apache2 | grep -v grep > /dev/null

if [ $? != 0 ]
then
        /etc/init.d/apache2 restart >> /var/log/uwe-crontab/crons.log
        echo "apache relaunched at $(date)" >> /var/log/uwe-crontab/crons.log
else 
        echo "apache is running"  >> /var/log/uwe-crontab/crons.log
fi

I try to run it from root’s cron. Here’s the cron entry.

* * * * * sh /etc/apache2/relaunch.sh

Strangely, the script fires every minute and writes an entry into my log file without a problem, but won’t work correctly when it is run from Cron. Is it some problem with environment variable? Maybe I need to set that in the script too?

If I stop Apache, the script still writes the the log file but doesn’t restart Apache.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.