bash: differing newline count when assigning result to variable
<p>let's say I want to see how many copies of a program are already running. I could do something like this:</p>

<pre><code>ps ax | grep -c "$0"
</code></pre>

<p>that command by itself produces the expected result. BUT if I attempt to assign the output to a variable, it gets incremented by one! No matter how I try it:</p>

<pre><code>var=$(ps ax | grep "$0" | sed -n '$=')
var=`ps ax | grep -c "$0"`
</code></pre>

<p>can someone please show me the right way to capture the correct output? </p>

<p>it would also be great to know why this is happening..</p>

<p>UPDATE 
after the first response from @fedorqui I realize I wasn't clear enough. let me elaborate:</p>

<p>I am running all three commands above in the same bash script. When I run the first one, it prints out the number 2: the program itself and the grep process with that program as an argument. when I run those same commands within variable assignments, the number 3 is stored.</p>

<p>please note that I am using two different methods of counting lines, grep and sed. in both cases they return 3 instead of the correct answer, 2. </p>

<p>here is a consolidated example to try in a test.sh file:</p>

<pre><code>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"
</code></pre>

<p>the results on my debian box:</p>

<pre><code>without assignment: 2
using sed method: 3
using grep method: 3
</code></pre>

<p>the questions again: why is this happening, and how to prevent or work around?</p>