如何在 bash 中的 grep 中指定命令行参数?

How to specify commandline arguments in pgrep in bash?

我有几个进程 运行 名称相同但命令行参数不同。

$ 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

如何根据进程的全名获取进程 ID,例如process_name 4010 127.0.0.1?

我试过使用 pgrep,但看起来这并没有考虑参数。

$ 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

使用 -f 选项匹配完整命令行:

pgrep -f 'process_name 4010 127.0.0.1'

这也将匹配 subprocess_name 4010 127.0.0.11。如果您想避免这种情况,请使用 ^ 在开头锚定匹配项,并在结尾处使用 $ 作为锚点:

pgrep -f '^process_name 4010 127.0.0.1$'

文档

来自man pgrep

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