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
Don't use
grep foo | grep -v grep
, that gets processed bygrep
when the shell executesgrep
, instead use[ ]
to get the pattern of your script name.Following fixed the issue
grep -cw "test.sh"