3

I'm trying to write a cron job script that will check if my services are running and restart them if they aren't so I don't have to do it manually.

Now, I've looked up online how to check the status of a service in a bash script, and have found basically the following, with a few variations:

ps auxw | grep <service_name> | grep -v grep

if [[ $? != 0 ]]; then
        /etc/init.d/<service_name> start
fi

I did some thinking and thought it might be a bit less hacky and more of a way of using the init script's general functionality to check it this way:

/etc/init.d/<service_name> status

if [[ $? != 0 ]]; then
    /etc/init.d/<service_name> start
fi

Please correct me if I'm wrong, but wouldn't this always work? Is this a property of init scripts in general, that they return that exit code? Thanks in advance. :)

  • Under what distribution? This is not the case in Debian, but it might be the case in your distribution. – Gilles Aug 31 '15 at 0:14
  • Ubuntu 14.04 LTS Server. It seemed to work for the services that I tested it on, but I wasn't sure if it would work for all of them. This is more of a curious question, because I can obviously try this myself, and see if it works. – Ethan Brouwer Aug 31 '15 at 0:15
2

Not 100% of the time. However, it's a very good yardstick.

CFEngine 3 uses this in "services promises" to check if services are running. If the exit code of /etc/init.d/<servicename> status is zero, it assumes the service is running.

I have just run into BitBucket's noncompliance with this convention: /etc/init.d/atlbitbucket status returns 0 even when it's not running. However, I would consider this to be undesirable behavior (a bug) in the init script, that it doesn't follow the convention.


Found a reference for it; the Linux Standard Base Specification states:

If the status action is requested, the init script will return the following exit status codes.

0         program is running or service is OK
1         program is dead and /var/run pid file exists
2         program is dead and /var/lock lock file exists
3         program is not running
4         program or service status is unknown
5-99      reserved for future LSB use
100-149   reserved for distribution use
150-199   reserved for application use
200-254   reserved

So yes, compliant applications can be counted upon to behave in this fashion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.