4

I just ran into a weird scenario, and I'm not sure if this is a feature, and if not, what sort of security implications does it represent? Likely nothing for grep, but other directory-crawling utilities, potentially?

Here's how to reproduce:

  • touch ./-vR
  • grep hi *

Notice that everything not hi is returned, recursively.

0

2 Answers 2

4

That's a known misfeature of GNU getopt (used for option parsing by GNU tools).

grep hi -vR

is required by POSIX to look for hi in the file called -vR as options many not be recognised past non-option arguments (like hi here).

Most GNU tools or tools making use or the GNU getopt API in the default mode don't honour that unless POSIXLY_CORRECT is in the environment.

So you need either:

POSIXLY_CORRECT=1 grep hi *

(force grep to behave in a POSIX compliant way) or

grep -- hi *

(explicitly mark the end of options with --) or

grep hi ./*

(make sure all file names start with ./, and so not -).

In any case, with:

grep -e hi -vR

you'd have the problem with GNU and non-GNU grep as that hi is not a non-option argument, but an argument to the -e option, so you'd need:

grep -e hi -- *

or (better as it also addresses the problem of a file called -):

grep -e hi ./*

(POSIXLY_CORRECT wouldn't help).

4

This is a "feature" of GNU grep (and other GNU utilities that does the command line parsing in the same way). The command line parsing routines that GNU uses allows for flags to be specified after what's supposed to be the final operand on the command line.

To work around this, explicitly tell the utility that there will be no more command line flags:

$ grep -- hi *

This forces grep to treat the filenames expanded from * by the shell as filenames and not as options.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .