Terminal: grep recursive - don't search in symlink contents

Solution 1:

If you look at the man page for grep, there is no option to exclude symlinks, and therefore an alternative method will need to be applied. One such method is to use find to output only file pathnames using the -type t option, where t is set to f for regular file.

Example:

 find . -type f -exec grep -l 'search' {} \; 

Where 'search' is whatever you're greping for, and the output will be the relative path filename of the file(s) containing it because of using -l with grep.

In the example above, grep will be executed for each relative path filename that find passes to
-exec. As grep can handle multiple filenames, you can change the ;, at the end of the command, to + to tell find to pass all the matching filenames to grep at once. Note that if the number of matching filenames is large, then the allowable length of the command line could be exceeded.

Also note that find has a rather large set of options, and as such you may be able to narrow down the output passed grep, depending on your needs.

Solution 2:

MacOS ships with BSD grep which doesn't seem to support a way to ignore symlinks. You can install GNU grep. Run it with the 'r' flag and it will ignore symlinks.

# Install GNU grep
brew install grep

# Run GNU grep, ignore symlinks.
# Brew doesn't replace system grep, GNU grep needs to be called with 2 g's.
ggrep -rl mypattern

# Run GNU grep, follow symlinks
ggrep -Rl mypattern