【问题标题】:Bash script process name regexBash 脚本进程名称正则表达式
【发布时间】:2011-04-16 15:55:46
【问题描述】:

我正在尝试根据进程名称的一部分对进程 ID 进行正则表达式。如果我只做一个单词,它似乎可以工作,但是当我尝试做类似的事情时它会失败:find me any process with path /beginning ** /endswiththis/

这是我目前所拥有的:

QUEUE_PID="$(ps -ef | grep endswiththis | grep -v $0 | grep -v grep | awk '{ print $2 }')";   

有什么想法吗? 谢谢, 史蒂夫

【问题讨论】:

    标签: regex bash unix grep


    【解决方案1】:

    现在许多 UNIX 都有 pgrep,它可以满足您的需求

    DESCRIPTION
       pgrep  looks  through the currently running processes and lists the process IDs which
       matches the selection criteria to stdout.  All the criteria have to match.
    

    举个例子:

    $ps -ef | grep sendmail
    simonp    6004 27310  0 09:16 pts/5    00:00:00 grep sendmail
    root      6800     1  0 Jul19 ?        00:00:03 sendmail: accepting connections
    smmsp     6809     1  0 Jul19 ?        00:00:01 sendmail: Queue runner@01:00:00 for /var/spool/clientmqueue
    
    $pgrep sendmail
    6800
    6809
    

    传递给pgrep 的参数是一个正则表达式 - 这与可执行文件名或依赖于参数的完整进程参数字符串 (-f) 匹配。

    $pgrep  '^sen.*il$'
    6800
    6809
    
    $pgrep -f '^sendmail.*connections$'
    6800
    

    更多信息

    man pgrep
    

    【讨论】:

    • 对正则表达式有什么想法可以得到任何与路径的开头和结尾相匹配的东西吗? /matchthis/ignore/ignore/andendwiththis/
    • @Steve: grep '/matchthis/.*/andendwiththis/'grep -E '/matchthis(/.*/|/)andendwiththis/'
    • @Dennis 成功了。我正在为匹配的术语使用变量,它似乎使它不起作用。有什么语法需要改变吗?
    • @Steve:将单引号 ' 更改为双引号 " 以允许扩展其中的变量。
    • 对不起,我想我需要更明确一点。路径站点=站点; procVar=initQueues; QUEUE_PID="$(ps -ef | grep '$pathSite.* $procName }' | grep -v $0 | grep -v grep | awk '{ print $2 }')";过程:/Applications/MAMP/bin/php5/bin/php /Projects/sitex/library/service/public/BackgroundService.php initQueues
    猜你喜欢
    • 2011-11-01
    • 2011-10-17
    • 2013-06-06
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    相关资源
    最近更新 更多