grep --include, --exclude, --exclude-dir
grep --include, --exclude, and --exclude-dir limit a recursive search to files and directories matching a glob.
A recursive grep on a checkout will scan node_modules and .git unless you scope it. These GNU filters keep the search fast and on-target.
What it does
With -r, grep --include=GLOB searches only files whose names match the glob, --exclude=GLOB skips matching files, and --exclude-dir=GLOB skips whole directories without descending into them. They are GNU grep features and can be repeated. --exclude-dir is far cheaper than --exclude because grep never enters the directory.
Common usage
# search only TypeScript sources
grep -rn --include='*.ts' "apiKey" .
# skip vendored and VCS directories
grep -rn --exclude-dir={node_modules,.git,dist} "TODO" .
# exclude lockfiles
grep -rn --exclude='*.lock' "version" .Options
| Flag | What it does |
|---|---|
| --include=GLOB | Search only files matching the glob |
| --exclude=GLOB | Skip files matching the glob |
| --exclude-dir=GLOB | Skip directories matching the glob entirely |
| -r | Required: these filters apply to recursive search |
In CI
Always add --exclude-dir={node_modules,.git} to recursive greps in a repo; it is the difference between a sub-second check and scanning tens of thousands of vendored files. The brace expansion {a,b,c} is shell syntax, so it works in bash but not in plain sh; repeat the flag for portability.
Common errors in CI
These flags are GNU-only: on BSD/macOS grep, --include and --exclude-dir exist in recent versions but older ones do not, raising "grep: unrecognized option". A check that mysteriously matches inside node_modules usually forgot --exclude-dir. The brace form fails under dash/sh; write the flags out individually if the CI shell is not bash.