Somesh Garje
Somesh Garje

Reputation: 95

Running a shell script to get correct process count

I am trying to run the below shell script test.sh

$service=$1
$count=`ps -ef |grep -i "$service" |grep -v grep | wc -l`
echo "$count"

Command: sh test.sh abcde

I am expecting the script to output 0 but it gives me 1.

PS: I will be running this script using shell_exec from a php file and input to script will be array elements from php file

Upvotes: 0

Views: 1145

Answers (1)

Barmar
Barmar

Reputation: 782564

You get 1 because the output of ps -ef include the command

sh test.sh abcde

and this is matched when you do grep -i "abcde". You need to filter this out for the same reason you filter out grep, so change

grep -v grep

to

grep -E -v 'grep|test\.sh'

Upvotes: 1

Related Questions