/etc insider

since 1999 (and still editing)

Don’t grep ps by PID

| Comments

Watching some video tutorials I notice sometimes tutors type in stuff similar to this way too often:

ps -e | grep 42

This is being done for finding if process with PID 42 is still being run, for e. g.. What’s really should be used instead is ps alone (not to mention fgrep instead of grep):

ps 42.

If you want to remember it, you’d better give it a try now: ps 1 – you always can expect to have init process running and by convention it’s PID 1. As can be seen (and remembered) ps alone can give you info about specified PID, and this is quite portable feature, it works the same way on Linux, FreeBSD, Mac OS X and you-name-it.

OTOH, grep still makes sense when searching by name indeed. It has own drawbacks, namely finding itself too but that’s something you can workaround with a clever old trick – just use square brackets:

ps -e | grep 'syslo[g]'

instead of ps -e | grep syslog

Text syslo[ doesn’t match pattern syslo[g]. Of course if you were looking for something with grep in name, this trick won’t do and this could be the time to use pgrep instead.

Comments