HPUX Scripting

Frog_1337
Frog_1337 used Ask the Experts™
on
I am writing a script to check if the snmpd service is running on a dev server. I have the script written but every time I run it the results come back that the service is running even if I have manually stopped the service. I am very confused with this. The script is below.

#!/bin/bash

OUTPUT=$(ps -ef | grep snmpd | wc -l)

if [ $OUTPUT -lt 1 ];
then
        echo "SNMPD is not running"
else
        echo "SNMPD is running"
fi
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2013
Top Expert 2013
Commented:
The problem is that grep will in most cases find its own command line in the ps list,
so the result will then be (at least) "1", even when the concerned process is not found.

There are two solutions I'm aware of:

#!/bin/bash
OUTPUT=$(ps -ef | grep snmpd | grep -v grep | wc -l)
if [ $OUTPUT -lt 1 ];
then
        echo "SNMPD is not running"
else
        echo "SNMPD is running"
fi

or

#!/bin/bash
OUTPUT=$(ps -ef | grep snmp[d] | wc -l)
if [ $OUTPUT -lt 1 ];
then
        echo "SNMPD is not running"
else
        echo "SNMPD is running"
fi

A shorter solution:

#!/bin/bash
if ps -ef | grep -q snmp[d]; then
        echo "SNMPD is running"
else
        echo "SNMPD is not running"
fi

Author

Commented:
That was it thank you so much
Most Valuable Expert 2013
Top Expert 2013

Commented:
You're always welcome, glad I could help!

Please consider accepting my comment as the solution.

Greetings

wmp

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial