Counting process instances with grep & wc [duplicate]

陌路散爱 提交于 2019-12-13 03:55:23

问题


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


回答1:


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

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



回答2:


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


来源:https://stackoverflow.com/questions/51600563/counting-process-instances-with-grep-wc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!