views:

61

answers:

1

I'm trying to regex process id's based on parts of a process name. It seems to work if I only do a single word, but it fails when I try to do something like: find me any process with path /beginning ** /endswiththis/

Here's what I have so far:

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

Any thoughts? Thanks, Steve

+2  A: 

Many UNIXes now have pgrep which does exactly what you want

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.

As an example:

$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

The parameter passed to pgrep is a regular expression - this is matched against either against the executable file name or the full process argument string dependent on parameters (-f).

$pgrep  '^sen.*il$'
6800
6809

$pgrep -f '^sendmail.*connections$'
6800

For more information

man pgrep
Beano
Any thoughts on the regex to get anything that matches the beginning of the path and the end? /matchthis/ignore/ignore/andendwiththis/
Steve
@Steve: `grep '/matchthis/.*/andendwiththis/'` or `grep -E '/matchthis(/.*/|/)andendwiththis/'`
Dennis Williamson
@Dennis that worked. I'm using variables for the matched terms and it seems to make it not work. Any syntax things that have to change?
Steve
@Steve: Change the single quotes `'` to double quotes `"` to allow the variables within to be expanded.
Dennis Williamson
Sorry, I think I need to be more explicit. pathSite=sitex;procVar=initQueues;QUEUE_PID="$(ps -ef | grep '$pathSite.* $procName }' | grep -v $0 | grep -v grep | awk '{ print $2 }')";Proc:/Applications/MAMP/bin/php5/bin/php /Projects/sitex/library/service/public/BackgroundService.php initQueues
Steve
Awesome. Thanks Dennis!
Steve