Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify commandline arguments in pgrep in bash?

I have few processes running with same name but different commandline arguments.

$ ps -ef | grep process_name 
myusername 19276 6408 0 18:12 pts/22 00.00.00 process_name 4010 127.0.0.1
myusername 23242 6369 0 18:32 pts/11 00.00.00 process_name 4010 127.0.0.2

How can I get the process id based on the full name of the process e.g. process_name 4010 127.0.0.1?

I tried using pgrep, but it looks like this does not look into arguments.

$ pid=$(pgrep process_name) 
19276 23242
$ pid=$(pgrep process_name 4010 127.0.0.1) #error
$ pid=$(pgrep "process_name 4010 127.0.0.1") #blank
$ pid=$(pgrep "process_name\s4010\s127.0.0.1") #blank
$ pid=$(pgrep "process_name[[:space:]]4010[[:space:]]127.0.0.1") #blank
like image 783
Sonu Mishra Avatar asked Jul 13 '16 01:07

Sonu Mishra


1 Answers

Use the -f option to match against full command line:

pgrep -f 'process_name 4010 127.0.0.1'

This will also match subprocess_name 4010 127.0.0.11. If you want to avoid that, use ^ to anchor the match at the beginning and $ as an anchor at the end:

pgrep -f '^process_name 4010 127.0.0.1$'

Documentation

From man pgrep:

-f, --full
The pattern is normally only matched against the process name. When -f is set, the full command line is used.

like image 169
John1024 Avatar answered Nov 07 '22 14:11

John1024