Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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. :)

share|improve this question
    
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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.