Exclude Directories from a Recursive grep Search
Skip directories in a recursive search with grep --exclude-dir. It matches the directory's name, so a path with a slash in it excludes nothing at all.
A search through a project returns the same hits again from vendored code and from .git.
mkdir -p src node_modules/pkg .git
echo needle > src/app.js
echo needle > node_modules/pkg/index.js
echo needle > .git/note
grep -rn needle . | sort
echo ---
grep -rn --exclude-dir=node_modules --exclude-dir=.git needle .
echo ---
grep -rn --exclude-dir=node_modules/pkg needle . | sort./.git/note:1:needle
./node_modules/pkg/index.js:1:needle
./src/app.js:1:needle
---
./src/app.js:1:needle
---
./.git/note:1:needle
./node_modules/pkg/index.js:1:needle
./src/app.js:1:needleEach --exclude-dir takes a glob, and grep skips any directory whose name matches while it descends. The GNU grep manual says the pattern is matched against the final component for a directory found while recursing. That explains the last block, where a pattern with a slash in it matches no directory name and every hit comes back. Braces cover several names at once, as in --exclude-dir={.git,node_modules}.
The brace form is expanded by Bash, not by grep, and a plain sh script gets it literally. A command line directory such as . is matched too, so --exclude-dir=. removes the whole search. For a path-based exclusion use find with -path ... -prune, or git grep, which honors .gitignore.