How can I prevent Bash expansion from passing files starting with "-" as argument?

First, note that the interpretation of arguments starting with dashes is up to the program being started, grep or other. The shell has no direct way to control it.

Assuming you want to process such files (and not ignore them completely), grep, along with most programs, recognizes -- as indicating the end of options, so

grep -r -e "stuff" -- *

will do what you want. The -e is there in case stuff starts with a - as well.

Alternatively, you can also use:

grep -r -e "stuff"  ./*

That latter one would also avoid the problem if there was a file called - in the current directory. Even after the -- separator, grep interprets - as meaning stdin, while ./- is the file called - in the current directory.


To prevent Bash expansion from passing files starting with “-” you can use:

echo [!-]*

Which works portably in most shells, or, specific to ksh, bash, zsh:

echo !(-*)

For example: in a directory with this files

$ echo *
a b c ---corporate-discount.csv d -e --option.txt

Will list only (provided extglob is active):

$ shopt -s extglob
$ echo !(-*)
a b c d

$ echo [!-]*
a b c d

But if what you want is to process all files while telling grep to avoid interpreting files stated with a - as options, then just add a ./:

grep -r "stuff" ./*

Or, if there is guarantee that no file called exactly - exists in the files listed (grep will interpret a lonely - as read from stdin), you can use:

grep -r -- "stuff" *

Tags:

Shell

Grep