In pseudo code I’m trying to do something like the following
if myService is running
restart myService
else
start myService
How can I translate the above into a bash script or similar?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The standard way is to use a PID file for storing the PID of the service. Then, you can use the PID stored in the PID file to see if the service is already running or not.
Take a look at the various scripts under the
/etc/init.ddirectory and see how they use the PID file. Also take a look under/var/runin most Linux systems to see where the PID files are stored.You can do something like this which is a generic way of handling this for all Bourne shell type shells:
However, on Linux, you can take advantage of pgrep:
Note how you do not use any braces. The
ifstatement operates on the exit status of thepgrepcommand. I’m outputting both STDOUT and STDERR to /dev/null because I don’t want to print them. I just want the exit status of thepgrepcommand itself.READ THE MANPAGE ON PGREP
There are quite a few options. For example, you might want to use
-xto prevent unintended matches, or you might have to use-fto match on the full command line used to start the service.