用grep和wc计数流程实例

时间:2018-07-30 18:58:40

标签: bash grep ps wc

我正在尝试使用以下命令对流程实例进行计数:

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

这在命令行上可以完美地工作,但是在脚本中,当我将输出分配给变量时:

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

输出:

2

它会增加1,我不知道为什么会发生。

如果我只在脚本中输入以下命令,它将正确打印

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

2 个答案:

答案 0 :(得分:0)

以下解决了问题grep -cw "test.sh"

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

答案 1 :(得分:0)

不要使用grep foo | grep -v grep,它会在shell执行grep时由grep处理,而是使用[ ]来获取脚本名称的模式。

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

-c counts the number of matches
相关问题