*Why* does using /dev/null in find/grep display the file name?

2

1

find . -name "*.java" -exec grep "foo" {} \;

This just prints matches, no file name.

find . -name "*.java" -exec grep "foo" /dev/null {} \;

But this prints file name as well.

Why? What are the mechanics of find/grep that cause file name to print when /dev/null is inserted into the mix?

PS - yes, I know I can do "grep -H"

Jonathan

Posted 2010-05-13T12:38:58.327

Reputation: 23

Answers

6

If you use neither the -h nor the -H option, then grep will write out the filename if more than one file is given as arguments. So if you add /dev/null as argument to grep, you will always have more than one, so the file name will always be written. But yeah, using ˛grep -H is the safest way to always have the filename written.

petersohn

Posted 2010-05-13T12:38:58.327

Reputation: 2 554

1

I would guess that grep, when searching multiple files, will output the file name in front of the matched line in order to differentiate where it found the line. Otherwise, if only one file is specified, the user already knows what file the line would be found in.

Use grep -h to turn off filenames in output, and grep -H to force them on.

amphetamachine

Posted 2010-05-13T12:38:58.327

Reputation: 1 443