0

this is my shell script

#!/bin/sh
echo "===="
echo $1
echo "===="
ps -ef | grep -w $1 | grep -v -e "grep" 
echo "===="
echo  $(ps -ef | grep -w $1 | grep -v -e "grep" | wc -l)
echo "===="
exit 0

then,i execute the shell script at command line.

./test.sh php-fpm

the result is:

====
php-fpm
====
0   986   984   0  4:43PM ??         0:05.53 php-fpm
70   988   986   0  4:43PM ??         0:00.00 php-fpm
70   989   986   0  4:43PM ??         0:00.00 php-fpm
70   990   986   0  4:43PM ??         0:00.00 php-fpm
0   984     1   0  4:43PM ttys000    0:00.01 sudo php-fpm
501  4098   827   0 10:24AM ttys001    0:00.00 /bin/sh ./test.sh php-fpm
====
7
====

so,my question is:why last output is 7 not 6?

thanks.

  • Calling $( ... ) creates subshell, so you have one more process. In detail its explained here: http://stackoverflow.com/questions/37801681/bash-inline-execution-returns-duplicate-process-why –  Dec 09 '16 at 03:13
  • you don't need `echo $( ...)`. Just run the `ps .... |wc -l ` pipeline without cmd-substitution. Good luck. – shellter Dec 09 '16 at 04:10
  • BTW, your program will show an incorrect result, if $1 contains *grep* as a substring, or if one of the processes displayed has the string *grep* in their arguments. – user1934428 Dec 09 '16 at 06:10

1 Answers1

1

You can use command

ps -C $1 --no-headers

Updated code is

#!/bin/sh
echo "===="
echo $1
echo "===="
ps -C $1 --no-headers
#ps -lfC $1 --no-headers
echo "===="
COUNT=$(ps -C $1 --no-headers | wc -l)
echo $COUNT
echo "===="
exit 0

Run

sh /tmp/test.sh java

O/P

====
java
====
4969 ?        00:01:00 java
6884 ?        00:00:34 java
10200 ?        00:00:18 java
====
3
====
Prakash
  • 163
  • 8