grep -r --exclude-dir=node_modules: skip directories in a recursive search
- tool
- grep
- command
- grep
- flag
- --exclude-dir=GLOB
- default
- no directory is excluded
grep -r --exclude-dir=node_modules "pattern" . searches the current directory recursively but does not descend into any directory named node_modules. The value is a glob matched against the directory's base name, not a path, so --exclude-dir=node_modules skips it at every depth. Repeat the option for several directories, or use shell braces: --exclude-dir={node_modules,.git,dist}.
Example
mkdir -p app/src app/node_modules/lib app/.git app/dist
echo 'TODO: fix login' > app/src/login.js
echo 'TODO: vendor code' > app/node_modules/lib/index.js
echo 'TODO: git internals' > app/.git/notes
echo 'TODO: built file' > app/dist/bundle.js
echo '--- all'
grep -r "TODO" app | sort
echo '--- one exclude'
grep -r --exclude-dir=node_modules "TODO" app | sort
echo '--- several'
grep -r --exclude-dir={node_modules,.git,dist} "TODO" app
echo "--- a path does not match"
grep -r --exclude-dir=app/node_modules "TODO" app | grep -c node_modulesOutput
--- all app/.git/notes:TODO: git internals app/dist/bundle.js:TODO: built file app/node_modules/lib/index.js:TODO: vendor code app/src/login.js:TODO: fix login --- one exclude app/.git/notes:TODO: git internals app/dist/bundle.js:TODO: built file app/src/login.js:TODO: fix login --- several app/src/login.js:TODO: fix login --- a path does not match 1
The braces are expanded by the shell (bash and zsh) into three separate --exclude-dir options; sh and other shells without brace expansion need the option written out three times.
What the value matches
| Value | Effect |
|---|---|
| --exclude-dir=node_modules | Skips every directory whose name is node_modules, at any depth |
| --exclude-dir='.*' | Skips hidden directories such as .git and .cache (quote the glob) |
| --exclude-dir=build* | Skips build, build-debug, buildtmp ... |
| --exclude-dir=src/vendor | Does not match: the value is compared with the base name, so use vendor instead |
Related options
| Option | Effect |
|---|---|
| --include=GLOB | Search only files whose base name matches GLOB |
| --exclude=GLOB | Skip files whose base name matches GLOB |
| --exclude-from=FILE | Read file exclusion globs from FILE, one per line |
| -I | Skip binary files |
--exclude-dir exists in GNU grep and in the BSD grep shipped with macOS. In a Git repository, git grep "pattern" searches only tracked files, so ignored directories such as node_modules are skipped without any option.