grep -c gives inconsistent outputs

I am trying to determine the number of processes that are running via the following command line:

ps aux | grep -c 'Xvfb :1'

When the process "fiji :1" is not running I sometimes get a value of 0 and other times a value of 1. The act of running the grep command seems to be counted sometimes and other times not.

Running the command line below gives consistently zero processes:

ps aux | grep 'fiji :1' | grep -v grep

Similar to adding the grep -v grep, is there a way to make "grep -c" count the number of processes running minus the grep command?

ps aux | grep Xvfb gives this:

60293 17250 0.0 0.1 45052 7016 pts/4 S Sep30 0:02 Xvfb :4 -screen 0 1600x1200x16 
60293 17373 0.0 0.0 40704 2964 pts/0 S Sep30 0:02 Xvfb :5 -screen 0 800x600x16 
60293 29695 0.0 0.1 42996 6112 pts/6 S 13:00 0:00 Xvfb :3 -screen 0 1600x1200x16 
60293 31650 0.0 0.0 61160 756 pts/6 R+ 13:58 0:00 grep Xvfb

pgrep 'Xvfb :3' | wc -l doesn't quite work because it returns 0 when there is actually 1 process running.

pgrep 'Xvfb' | wc -l returns 3 which is correct.

I also tried pgrep 'Xvfb :3 -screen 0 1600x1200x16' | wc -l and it incorrectly returned 0.

Seems like pgrep doesn't like the space in Xvfb :3?


Solution 1:

By default, pgrep checks the process name – which by default is the executable file name truncated to 16 bytes. To check the full command line as in ps aux, use the -f option.

pgrep -f "Xvfb" | wc -l

Compare: pgrep -l "Xvfb" and pgrep -lf "Xvfb".