-1

I'm trying to search a directory of files for occurences of the literal string -d /data/. When I try using grep, I get an error due to the fact that -d is a grep flag:

$ grep -F "-d /data" files/* grep: invalid argument ‘ /data’ for ‘--directories’ Valid arguments are: - ‘read’ - ‘recurse’ - ‘skip’ Usage: grep [OPTION]... PATTERNS [FILE]... Try 'grep --help' for more information. 

This answer says to use the -F flag for grep to force it to search for a string literal, but as you can see, I already am. I've also tried fgrep and using single quotes instead of double quotes; it makes no difference. I've tried escaping the - with a backslash:

$ grep -F "\-d /data" files/* 

which causes grep to return zero hits even though I know for a fact that there are occurrences of -d /data to find.

How do I execute this grep search?

0

1 Answer 1

2

That's an easy one.

Just insert "--" after the options and before the arguments, like grep -- -d *

This works for many unix commands, especialy valuable for rm, if some dork named a file that begins with a "-".

2
  • It's not that bad with rm. It can get a lot worse including introducing arbitrary command execution vulnerabilities with some other utilities such as sed, which is why it's critical not to forget the -- in sed -e '...' -- *.txt for instance or even sed -- '...' *.txt with GNU sed (especially GNU sed's which has commands that can execute commands) or the other sed implementations that accept options after non-option arguments. sed and rm can also avoids that issue (and more) with rm ./-d or sed ... ./-d. Commented Sep 13 at 9:26
  • @StéphaneChazelas It can always get worse. "And, out of the chaos, a voice spoke unto me: smile, and be happy, it could get worse. And I smiled. And was happy. And it did get worse". Joke aside, what you are telling is one reason why most SQL-implementations have *prepared statements", so some jester entering "';drop all tables;' " can't do harm. Commented Sep 14 at 19:39

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.