Ubuntu – Difference between grep -R (uppercase) and -r (lowercase)

command linegrep

If I go into /etc/apache2/ and type grep -rl 'LoadModule php' ./* then I'll only see ./mods-available/php7.0.load. If I change r to R then I'll see

./mods-available/php7.0.load
./mods-enabled/php7.0.load

Both of these are plain directories. I'd expect -r to cause grep to recurse all files/dirs in the PWD. What's going on with -r? I'm minded to just always use -R at this point.

Best Answer

According to manpage of grep:

-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.

-R, --dereference-recursive
               Read all files under each directory, recursively. Follow all symbolic links, unlike -r.

Example:

I have a folder test in which there is a file 1.txt. 2.txt is a symbolic link to 1.txt such that output of ls -l test looks like:

-rw-r--r-- 1 kulfy kulfy 15 Jun 12 21:53 1.txt
lrwxrwxrwx 1 kulfy kulfy  5 Jun 12 21:53 2.txt -> 1.txt

The content of 1.txt is:

This is a file.

If I want to search for "file" string in files inside test folder and I run:

grep "file" test

I'll encounter an error:

grep: test: Is a directory

But if I do:

grep -R "file" test

I get an output:

test/2.txt:This is a file
test/1.txt:This is a file

On the other hand if I run:

grep -r "file" test

I get output:

test/1.txt:This is a file

Here, I haven't explicitly mentioned to scan all the files. So, when I used R flag, symbolic link (here 2.txt) was respected and output was generated. But when I used r flag, symbolic link was ignored simply because I didn't mention to scan 2.txt also.

Related Question