4

Normally while searching using grep, the command I was using was this:

grep -nri "String"

whereas most of my colleagues do this:

grep -nri "String" *

What does the latter do (the * part)?

1 Answer 1

8

grep with the -r flag operates on all files in the specified directories recursively:

-r, --recursive
      Read all files  under  each  directory,  recursively,  following
      symbolic  links only if they are on the command line.  Note that
      if  no  file  operand  is  given,  grep  searches  the   working
      directory.  This is equivalent to the -d recurse option.

By default, if no directories are given, then grep will process all files in the current directory.

In grep -r ... *, then, the shell expands * to all files and directories in the current directory (usually except those that begin with a .), and grep then works recursively on them.

So, if you had a directory that contained, for example:

.git/
.gitignore
foo/
foo/.foo2
foo/link2 -> /foo2/bar2
bar
link1 -> /foo/bar

where the names ending with / are directories, then grep -r would also process the .gitignore file and everything in .git, but grep -r ... * would exand to grep -r ... foo bar, and would end up excluding .gitignore and .git (but it would include foo/.foo2).

Also note the point about symbolic links - if one of the files in the expansion of * was a symlink, the symlink target would be processed if you used *. So with *, /foo/bar will be processed as the target of link1, but not /foo2/bar2 as the target of link2.

The overall effect:

                                 w/o *           with *
.git/                              +                -
.gitignore                         +                -
foo/                               +                +
foo/.foo2                          +                +
foo/link2 -> /foo2/bar2            -                -
bar                                +                +
link1 -> /foo/bar                  -                +

Which you want to do, of course, depends on whether you want those files and directories included in the search; but I tend to prefer having grep itself do the excluding and including using the --exclude/--include and other options.

1
  • 2
    Ninja'd. Just what I wanted to say as well...
    – Byte Commander
    Apr 27, 2018 at 10:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .