4

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

Steve
  • 341
  • 1
  • 4
  • 9

1 Answers1

5

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
  • 7,551
  • 3
  • 24
  • 27
  • Any thoughts on the regex to get anything that matches the beginning of the path and the end? /matchthis/ignore/ignore/andendwiththis/ – Steve Sep 24 '10 at 15:19
  • 1
    @Steve: `grep '/matchthis/.*/andendwiththis/'` or `grep -E '/matchthis(/.*/|/)andendwiththis/'` – Dennis Williamson Sep 24 '10 at 15:43
  • @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 Sep 24 '10 at 17:07
  • 1
    @Steve: Change the single quotes `'` to double quotes `"` to allow the variables within to be expanded. – Dennis Williamson Sep 24 '10 at 17:15
  • 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 Sep 24 '10 at 17:17
  • Just watch out for the name limit. The above post mentions -f, but without this the pgrep match is truncated. Caught me out as I didn't note the significance. -l is great also to list the options. – Goblinhack Dec 16 '14 at 14:31