Thursday 4 March 2010

Poor mans pgrep on Mac OS X

pgrep on [Open-]Solaris, Linux et al is very convenient. I was missing it on Mac OS X. In it's simplest form, emulate it by creating the following shell script somewhere in your path or alias it:

#!/bin/sh
ps -axo pid,command,args | grep -i "$@" | awk '{ print $1 }'

This yields the output you're used to:

foo:~$ pgrep postgres
2853
2856
2857
2858
2859
3057
3059

I like to see the full process args with that. A slight tweak:

#!/bin/sh
pids=`ps -axo pid,command,args | grep -i "$@" | awk '{ print $1 }' | tr '\n' ','`
ps -p $pids -o pid,args

Gives you:

foo:~$ pgrep postgres         
PID ARGS
2853 /opt/lib/postgresql84/bin/postgres -D /opt/var/db/postgresql84/d
2856 postgres: writer process                                        
2857 postgres: wal writer process                                    
2858 postgres: autovacuum launcher process                           
2859 postgres: stats collector process                               
3166 /bin/sh /Users/imfeldma/bin/pgrep postgres

Nothing stops you from replacing ps with kill to obtain a poor mans pkill. Enjoy.

UPDATE: Of course you may also install proctools via MacPorts or directly from Sourceforge: http://sourceforge.net/projects/proctools/

2 comments:

  1. Thanks.

    More tunning: remove pgrep.sh process from listing by adding grep -v "$0 $@" to $pids pipe.

    ReplyDelete
  2. Don't have an OS X machine to try it out, but this is pretty portable:

    ps -u $USERNAME -o pid=

    ReplyDelete