2

I just encountered that the output of wc -l differs when called directly or enclosed in backticks. For example:

pgrep bash | wc -l

would output 1, as there is one bash process running. But enclosing this command in backticks

echo `pgrep bash | wc -l`

would output 2. I first thought, the backticks would open a new bash process, but

echo `pgrep bash`

does only find the same one process as above. The same is when enclosing the command in $():

echo $(pgrep bash | wc -l)

This will also output 2. Does somebody know why that is so?

Volker Stolz
  • 7,274
  • 1
  • 32
  • 50
Mike
  • 21
  • 1
  • 2
    I guess it's the pipe in the backticks, because `echo "pgrep bash | cat"` (just imagine the double quotes being backticks :)) also returns 2 PIDs, but putting 2 or more pipes in the command didn't change the number of PIDs returned. – Jacob Aug 24 '11 at 16:29
  • @cularis: You should post this as an answer (I was just about to). – Keith Thompson Aug 24 '11 at 16:37
  • @Manny: No, that's not it. `echo \`pgrep bash\`` prints the PIDs on one line, but in `echo \`pgrep bash | wc -l\`` the `wc` command sees one PID per line. (Yes, you can escape backticks with backslashes!) – Keith Thompson Aug 24 '11 at 16:39
  • @Keith I have no documentation/other support for my theory, it was just a quick test. Feel free to write an answer :) – Jacob Aug 24 '11 at 16:43

2 Answers2

1

@cularis should really get the credit for this, since he posted it as a comment (just) before I had a chance to post it as an answer.

Apparently

pgrep bash | wc -l

doesn't create a new bash process; it's able to invoke pgrep bash and wc -l from the original bash process directly.

But

echo `pgrep bash | wc -l`

does create a new bash process because of the pipe (a new process is the easiest way to manage all the I/O redirection and process management needed for the | nested within backticks). So in this case, pgrep bash sees the newly created bash process used to handle the pipe, in addition to the original (interactive/) process used to execute the command.

Try

pgrep bash

and

echo `pgrep bash | cat`

In a very quick look at the bash documentation (info bash, section 3.5.4, Command Substitution) I don't see anything that says when it creates a new process and when it doesn't.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
0

Thanks for your help guys. I actually found a better solution. Instead of using wc -l I should have just use the -c argument, which does only print the count of matching processes. Well, RTFM again. ;-)

Mike
  • 1