【问题标题】:How to specify commandline arguments in pgrep in bash?如何在 bash 中的 grep 中指定命令行参数?
【发布时间】:2016-11-15 10:22:54
【问题描述】:

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

$ 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

【问题讨论】:

    标签: bash shell process grep


    【解决方案1】:

    使用-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
    模式通常只匹配进程 姓名。设置 -f 时,使用完整的命令行。

    【讨论】:

    • -x for --exact 避免插入符号。
    猜你喜欢
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 2011-06-28
    • 2011-06-17
    • 2010-09-16
    • 1970-01-01
    相关资源
    最近更新 更多