Starting a Linux process only if it isn't started

Support forum for Nagios Core, Nagios Plugins, NCPA, NRPE, NSCA, NDOUtils and more. Engage with the community of users including those using the open source solutions.
Post Reply
drewdavis
Posts: 1
Joined: Sun Apr 21, 2024 11:23 pm

Starting a Linux process only if it isn't started

Post by drewdavis »

I am writing a bash script that launches a service (in my case nagios). I want to start my script by running /etc/init.d/nagios start only if nagios is not running.

I start my script with

/etc/init.d/nagios stop
/etc/init.d/nagios start
...

I'm not sure it is the best way to go, I'd rather use an if statement. Any ideas ?
bbahn
Posts: 118
Joined: Thu Jan 12, 2023 5:42 pm

Re: Starting a Linux process only if it isn't started

Post by bbahn »

Hello @drewdavis,

You can definitely accomplish what you're thinking of using something like the following:

Code: Select all

# Check if Nagios is running with /etc/init.d/nagios status, pgrep, systemctl status, ps aux | grep, etc.

# $? holds the exit status of the last command
if [ $? -ne 0 ]; then
    echo "Nagios is not running. Starting Nagios..."
    /etc/init.d/nagios start
else
    echo "Nagios is already running."
fi
April: Actively advancing awesome answers with ardent alliteration, aptly addressing all ambiguities. Amplify your acumen and avail our amicable assistance. Eagerly awaiting your astute assessments of our advice.
Post Reply