let's say I want to see how many copies of the program are already running. I could do something like this:
ps ax | grep -c "$0"
this command alone produces the expected result. BUT, if I try to assign the output to a variable, it will increase by one! No matter how I try:
var=$(ps ax | grep "$0" | sed -n '$=')
var=`ps ax | grep -c "$0"`
Can someone please show me the correct way to capture the correct output?
it would be great to know why this is happening.
UPDATE after the first reply from @fedorqui, I understand that I was not clear enough. let me clarify:
I execute all three commands above in the same bash script. When I run the first one, it prints number 2: the program itself and the grep process with this program as an argument. when I run the same commands in variable assignments, number 3 is saved.
Note that I use two different string counting methods, grep and sed. in both cases they will return 3 instead of the correct answer, 2.
here is a summary example to try in the test.sh file:
echo -n "without assignment: "
ps ax | grep -c "$0"
var=$(ps ax | grep "$0" | sed -n '$=')
echo "using sed method: $var"
var=`ps ax | grep -c "$0"`
echo "using grep method: $var"
the results in my debian block:
without assignment: 2
using sed method: 3
using grep method: 3
questions again: why is this happening, and how to prevent or get around?