14

Why do brackets in a grep pattern remove the grep process from ps results?

$ ps -ef | grep XXXX

[...] XXXX
[...] grep XXXX


$ ps -ef | grep [X]XXX

[...] XXXX
2

2 Answers 2

24

When you run ps -ef | grep string, grep is displayed in the output because string matches [...] grep string.

But, when you run ps -ef | grep [s]tring the line isn't displayed, because grep translates [s]tring to string, while ps outputs [...] grep [s]tring, and that doesn't match string

2
  • 1
    ...because [] represents any one of the set of characters within the brackets of which, in this case "s" is the only one... Sep 16, 2010 at 1:53
  • yea... I really had trouble trying to explain this one in english... it's not my first language :)
    – Stefan
    Sep 16, 2010 at 8:50
1

Because the brackets need to be escaped, for bash once and for grep again:

$ ps -ef | grep \\[X\\]XXX

[...] XXXX
[...] grep XXXX


$ ps -ef | grep "\[X\]XXX"

[...] XXXX
[...] grep XXXX

You must log in to answer this question.