Sonu Mishra Sonu Mishra - 3 months ago 6
Bash Question

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
myusername 23242 6369 0 18:32 pts/11 00.00.00 process_name 4010

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

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

$ pid=$(pgrep process_name)
19276 23242
$ pid=$(pgrep process_name 4010 #error
$ pid=$(pgrep "process_name 4010") #blank
$ pid=$(pgrep "process_name\s4010\s127.0.0.1") #blank
$ pid=$(pgrep "process_name[[:space:]]4010[[:space:]]") #blank


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

pgrep -f 'process_name 4010'

This will also match subprocess_name 4010 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$'


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.