Function of second grep in `ps | grep -v | grep`

grepps

ps aux  | grep firefox

Lists all processes having the string "firefox"

ps aux  | grep -v firefox

Lists all the processes without the string "firefox"

ps aux | grep -v grep | grep firefox ?

What does this second grep does ? grep itself is a command then why we are grepping another grep ?

Best Answer

When you do a command such as

ps aux  | grep firefox

Then the grep process itself may show in the output because the word you are looking for is present. e.g. on my machine I run chrome and the similar results:

% ps aux | grep chrome
sweh      3384  0.0  0.0  11128  1024 pts/1    S+   07:08   0:00 grep chrome
sweh     23698  0.0  0.0   6384   620 ?        S    Jul04   0:00 /usr/lib/chromi

We can see process 3384 is the grep command and matches because the word chrome shows up.

To avoid this some people then add a second | grep -v grep to remove that line.

There is a cheat though...

ps aux | grep '[f]irefox'

grep '[f]irefox' matches exactly the same lines as grep firefox, but now the grep command will never match itself because the word doesn't literally appear on that command.

Related Question