Grepping ps Output Without Also Getting the grep Process Itself
Problem
You want to grep output from the ps command without also getting the grep process itself.
Solution
Change the pattern you are looking for so that it is a valid regular expression that will not match the literal text that ps will display:
$ ps aux | grep 'ssh'
root 366 0.0 1.2 340 1588 ?? Is 20Oct06 0:00.68 /usr/sbin/sshd
root 25358 0.0 1.9 472 2404 ?? Ss Wed07PM 0:02.16 sshd: root@ttyp0jp 27579 0.0 0.4 152 540 p0 S+ 3:24PM 0:00.04 grep ssh
$ ps aux | grep '[s]sh'
root 366 0.0 1.2 340 1588 ?? Is 20Oct06 0:00.68 /usr/sbin/sshd
root 25358 0.0 1.9 472 2404 ?? Ss Wed07PM 0:02.17 sshd: root@ttyp0
Discussion
This works because [s]
is a
regular expression character class containing a single lowercase letter
s
, meaning that [s]sh
will match ssh
but not the literal string grep [s]sh
that ps will
display.
The other less efficient and more clunky solution you might see is something like this:
$ ps aux | grep 'ssh' | grep -v grep
See Also
man ps
man pgrep
man grep
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.