问题
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