When is it useful to use "grep -- SOMEPATTERN"?

When "SOMEPATTERN" starts or may start (for instance if it's a variable like "$PATTERN" which you don't have full control on) with a - (dash) character.

Also with GNU grep (unless $POSIXLY_CORRECT is on), it's useful if other arguments (file names) may start with -.

Alternatively, you can do

grep -e -SOMEPATTERN- -- file1 file2 -xxx-

-- marks the end of options. It's useful everywhere where non-option arguments may start with a dash, and it doesn't harm, so it's a good habit to use it.


When the pattern starts with a dash, otherwise grep will think it is an option. Say, you are looking for "-a" in a text:

grep -a file.txt

grep will then try to find the pattern "file.txt" in the standard input, using the option -a. Therefore, you need to do

grep -- -a file.txt