Every so often I will find myself writing a
grep
invocation like this:
find .... -exec grep <something> /dev/null '{}' '+'
The peculiar presence of
/dev/null
here is an old Unix trick that is designed to force
grep
to always print out file names, even if your
find
only matches one file, by always insuring that grep has at least two files as arguments. You can wind up wanting to do the same thing with a direct use of
grep
if you're not certain how many files your wildcard may match. For example:
grep <something> /dev/null */*AThing*
This particular trick is functionally obsolete because pretty much all modern mainstream versions of grep support a
-H
argument to do the same thing (as the inverse of the
-h
argument that always turns off file names). This is supported in GNU grep and the versions of
grep
found in FreeBSD , OpenBSD , NetBSD , and Illumos . To my surprise,
-H
is not in the latest Single Unix Specification
grep
, so if you care about strict POSIX portability, you still need to use the
/dev/null
trick.
( I am biased , but I am not sure why you would care about strict POSIX portability here. POSIX-only environments are increasingly perverse in practice (arguably they always were).)
If you stick to POSIX
grep
you also get to live without
-h
. My usual solution to that was
cat
:
cat <whatever> | grep <something>
This is not quite a pointless use of
cat
, but it is an irritating one.
For whatever reason I remember
-h
better than I do
-H
, so I still use the
/dev/null
trick every so often out of reflex. I may know that
grep
has a command line flag to do what I want, but it's easier to throw in a
/dev/null
than to pause to reread the manpage if I've once again forgotten the exact option.