Ender phan
Ender phan

Reputation: 185

multiple grep command in Linux

Just a basic question about grep command line. I found the way how to know that the service is running in process by using this command line:

ps -ef |grep -v grep | grep mongodb

I'm confused about the second grep:

|grep -v grep |

Why I need to use the "grep" after " -v " ???

What is the different between that command and this command ?

ps -ef |grep mongodb

Thank you!

Upvotes: 1

Views: 595

Answers (2)

Paul
Paul

Reputation: 297

The -v option tells grep not to let through anything matching the pattern, in this case lines that contain the string "grep". So if you omit the grep -v grep your grep process itself would also be displayed in the output after the second command in the pipe (and also after the third, as the grep process itself contains the word "mongodb").

Upvotes: 0

P....
P....

Reputation: 18351

When you grep "mongodb" through command line, your command also contains the word "mongodb" . So you will get two results. Which is flawed result. grep -v is to remove the grep command typed by user.

sh-4.1$ ps -ef |grep -v grep | grep mongodb
ps   17308 30074  0 06:05 pts/300  00:00:00 sh mongodb

vs

sh-4.1$ ps -ef |grep mongodb
ps   17308 30074  0 06:05 pts/300  00:00:00 sh mongodb
ps   17456 30074  0 06:05 pts/300  00:00:00 grep mongodb  #<<<This also contains mongodb word. Hence result is flawed. 

Upvotes: 2

Related Questions