Trick grep not to report itself in a process search

How often have you searched for a process, using ps and grep?

$ ps -ef |grep emacs
peter     7107     1  1 09:10 ?        00:00:08 /usr/bin/emacs-snapshot-gtk
peter     7377  7050  0 09:19 pts/0    00:00:00 grep emacs

It always reports one more process than you want to see … namely the grep process itself.

In the example above, the process 7377 is the grep process itself. What you really want is the 7107 emacs process.

While this is really harmless (albeit annoying), it can be a real pain if you put this in a script. In that case, you have to parse out the grep process itself.

You can trick grep not to report itself by enclosing a character in the search string in square brackets:

$ ps -ef |grep emac[s]
peter     7107     1  1 09:10 ?        00:00:10 /usr/bin/emacs-snapshot-gtk

Square brackets in bash are character matching patterns. emac[s] will only match the stringĀ emacs.