Matthias Ronge
Matthias Ronge

Reputation: 10122

Strange behaviour of grep command

When I do the following grep I get results I cannot explain to myself:

host:/usr/local/tomcat > grep '-XX:PermSize=256m' *
RELEASE-NOTES:      http://www.apache.org/licenses/LICENSE-2.0
RUNNING.txt:      http://www.apache.org/licenses/LICENSE-2.0

Afaik, none of the characters in my regular expression have a special meaning (inside square brackets, - has one, but there are none). I also put it into single quotes so it shouldn’t be modified by the shell.

Upvotes: 3

Views: 1770

Answers (3)

Matthias Ronge
Matthias Ronge

Reputation: 10122

The shell expands the command to the following:

grep -XX:PermSize=256m LICENSE NOTICE RELEASE-NOTES RUNNING.txt bin conf lib …

Grep accepts a secret parameter -Xoptarg without reporting an invalid option. In the source code it reads

  /* -X is undocumented on purpose. */

However, the next token, LICENSE is taken as regular expression. Typing grep -X * takes the LICENSE token as input string to the parameter -X and greps for NOTICE in RELEASE-NOTES and RUNNING.txt.

The meaning of the secret grep capital X parameter is to set the internal mode, i.e.

  • grep -X grep → behave normally (grep -G)
  • grep -X egrep → behave like grep -E
  • grep -X awk → uses RE_SYNTAX_AWK
  • grep -X fgrep → behave like grep -F
  • grep -X perl → behave like grep -P
  • grep -X 'unrecognized string' → behave normally

Upvotes: 3

Tilman Vogel
Tilman Vogel

Reputation: 9792

My grep complains about

grep: invalid matcher X:PermSize=256m

but what you can see here is that grep considers -X... as an option. To make it stop interpreting options, use --, i.e.

grep -- -XX:PermSize=256m *

The single-quotes are not necessary.

Upvotes: 2

devnull
devnull

Reputation: 123648

Since your pattern begins with a minus sign -, grep interprets it as an argument.

You could say:

grep -- '-XX:PermSize=256m' *

-- would tell grep to stop processing command line arguments.

Alternatively, you could say:

grep -- '[-]XX:PermSize=256m' *

(When you say [-] the hyphen is interpreted as a literal. Since you say (inside square brackets, - has one.., it seemed that it should be clarified.)

Upvotes: 4

Related Questions