Counting process instances with grep & wc [duplica

2019-08-20 19:59发布

This question already has an answer here:

I am trying to count process instances using the following command:

$ ps -ef | grep "test.sh" | egrep -v "grep|vi|more|pg" | wc -l
1

Which works perfectly on the command line, but in the script when I assign the output to a variable:

script_instances=`ps -ef | grep "test.sh" | egrep -v "grep|vi|more|pg" | wc -l`
echo $script_instances

Outputs:

2

It increments by 1, which I don't understand why it's happening.

If I just put following command in script it prints correctly

ps -ef | grep "test.sh" | egrep -v "grep"

Output:

root 14243 12162 0 19:12 pts/1 00:00:00 sh test.sh

I am on Ubuntu 14.04.5 LTS

标签: bash grep ps wc
2条回答
三岁会撩人
2楼-- · 2019-08-20 20:23

Don't use grep foo | grep -v grep, that gets processed by grep when the shell executes grep, instead use [ ] to get the pattern of your script name.

$ ps -ef | grep -c '[te]st.sh'

-c counts the number of matches
查看更多
beautiful°
3楼-- · 2019-08-20 20:27

Following fixed the issue grep -cw "test.sh"

script_instances=`ps -ef | grep -cw "test.sh" | egrep -v "grep|vi|more|pg" | wc -l`
查看更多
登录 后发表回答