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

Son*_*hra 5 bash shell grep process

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

$ 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
Run Code Online (Sandbox Code Playgroud)

如何根据进程的全名获取进程 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
Run Code Online (Sandbox Code Playgroud)

Joh*_*024 5

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

pgrep -f 'process_name 4010 127.0.0.1'
Run Code Online (Sandbox Code Playgroud)

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

pgrep -f '^process_name 4010 127.0.0.1$'
Run Code Online (Sandbox Code Playgroud)

文档

来自man pgrep

-f, --full
模式通常只与进程名称匹配。设置 -f 时,将使用完整的命令行。