Skip to content

/flags/grep/grep-exclude-dir

grep -r --exclude-dir=node_modules: skip directories in a recursive search

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · grep (GNU grep) 3.0updated
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

bash
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_modules

Output

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

ValueEffect
--exclude-dir=node_modulesSkips 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/vendorDoes not match: the value is compared with the base name, so use vendor instead
OptionEffect
--include=GLOBSearch only files whose base name matches GLOB
--exclude=GLOBSkip files whose base name matches GLOB
--exclude-from=FILERead file exclusion globs from FILE, one per line
-ISkip 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.

Sources