用grep&计数流程实例厕所 [英] Counting process instances with grep & wc
问题描述
我正在尝试使用以下命令对流程实例进行计数:
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
输出:
2
它增加了1,我不知道为什么会发生.
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"
输出:
root 14243 12162 0 19:12 pts/1 00:00:00 sh test.sh
我正在使用Ubuntu 14.04.5 LTS
I am on Ubuntu 14.04.5 LTS
推荐答案
不要使用grep foo | grep -v grep
,当shell执行grep
时,该grep foo | grep -v grep
由grep
处理,而是使用[ ]
来获取您的脚本名称.
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
这篇关于用grep&计数流程实例厕所的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!