Don't Match Yourself, Grep!
If you tend to ps|grep
, you’ve probably noticed it tends to match its own process, because the search string matches itself:
$ ps -a | grep worker.go
16849 ttys002 0:00.14 go run worker.go
16917 ttys004 0:00.00 grep worker.go
We were looking for the top one - but the grep matched itself too. if you were planning on sending the output through a pipeline, you’re going to end up with an additional entry for grep
itself.
The most elegant solution I’ve found requires only 2 more characters. If you merely turn one of the characters in your search term into a character set containing only that character, your search term won’t match itself. For instance:
$ ps -a | grep [w]orker.go
16984 ttys002 0:00.14 go run worker.go
Perhaps it’s a bit obscure, but it works. Just remember this won’t be compatible with grep -F
; since it disables regexes and does an exact text match, it won’t work with a character set (eg [w]
). If it’s not an option , you could stoop to using the clumsy invocation:
ps -a | grep -F ... | grep -v grep