For the want of pgrep on Mac OSX

I’ve got an issue at work, of course. I’ve got a Mac OSX xServer that has grown crotchety and so I’ve gotten to making things better by using killall on various running processes in order to “clean up the mess”. This is all fine and good and these processes respawn and the world goes back to normal and everything is fine, however I also want to renice this pesky command and give it a lower priority. While killall can do a search by name, renice requires a pid. The way you get pids is to run the ‘ps’ command, but this gives you a big pile of data and really all you want is just the pid itself, so you can pass that to renice.

So here’s how to get your cake and eat it too on Mac OSX Leopard Server:

1) First, change your shell – the default for root is /bin/sh, do this by issuing this command:

chsh -s /bin/bash root

2) Then you’ll need to give bash a profile, create a new file call it .bash_profile and fill it with this text:

[[ -s ~/.bashrc ]] && source ~/.bashrc

3) Next you’ll need to fill out that .bashrc because that contains the function you need to replicate pgrep:

pgrep() for arg; do ps aux|grep $1|grep -v grep|awk '{print $2}';done;

4) Log out and log back in and you’ll end up in bash, not sh, and you’ll have a new command at your disposal, pgrep. You can then use pgrep CommandName and it’ll spit out the pid related to what you are after.

5) Then you can use this new function with renice this way:

renice 20 `pgrep CommandName`

One thing to note here is that the ` character is the backtick character. You’ll find this hiding out in the upper left corner of your keyboard, it’s the unshifted tilde button.