Bash: different in the number of new lines when assigning the result to a variable

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?

+4
source share
3 answers
  • Language substitution itself is performed in a subshell, so that one bashprocess

  • bash ($0) i.e. grep -c bash , (grep) bash. , , , .

  • ( - ) bash (),

Regex, i.e. grep count:

ps ax | grep -c "[b]ash"

:

var=$(ps ax | grep -c "[b]ash")

, .

:

$ var=$(ps ax | grep -c "bash")    
$ echo $var
4

$ var=$(ps ax | grep -c "[b]ash")   
$ echo $var
3
+1

Siegex:

grep ps.

:

"" grep, , [ ], :

, ,

grep -v grep, :

var=$(ps ax | grep -v grep | grep "$0")

. . sleep:

$ sleep 20 &
[1] 5602

ps, !

$ ps -ef| grep sleep
me   5602  5433  0 09:49 pts/2    00:00:00 sleep 20
me   5607  5433  0 09:49 pts/2    00:00:00 grep --colour=auto sleep

, :

$ ps -ef| grep [s]leep
me   5602  5433  0 09:49 pts/2    00:00:00 sleep 20

grep:

$ ps -ef| grep sleep | grep -v grep
me   5602  5433  0 09:49 pts/2    00:00:00 sleep 20
+3

grep.

ps ax | grep -v grep | grep -c "$0"

grep count

0

All Articles