git grep
Search for text in tracked files
The 'git grep' command searches the files Git tracks and prints every matching line with its file name. It is faster than a normal grep on big projects, skips untracked and ignored files (like node_modules), and can search any commit or branch without checking it out.
Synopsis
git grep [<options>] <pattern> [<tree>...] [--] [<pathspec>...]Options
Choosing the Right Option
git grep vs grep
Why use Git’s own search
| Command | Searches | Old versions |
|---|---|---|
grep -r | Every file on disk, including node_modules | No |
git grep | Only tracked files | Yes: git grep x <commit> |
Examples
Search text
git grep "cart"Every line of every tracked file containing cart.
With line numbers
git grep -n "cart"Adds the line number.
In another commit
git grep "cart" v1.0Search the project as it was at v1.0.
Only some files
git grep "TODO" -- "*.js"Limit the search to JavaScript files.
Workflow Examples
git grep -n "count("Every call with its line
git grep -l "count("The list of files to edit
Troubleshooting
No output, exit code 1
Cause: Nothing matched
Check spelling, try -i, or check that the file is tracked
A file you just created is not searched
Cause: git grep only searches tracked files
git add it, or use git grep --untracked
Tips & Pitfalls
Best Practices
- ✓Enable line numbers once: git config --global grep.lineNumber true.
- ✓Search old releases with git grep <pattern> <tag> instead of checking them out.
Common Mistakes
- ✗Expecting untracked files in the results — add them first, or use --untracked.
- ✗Forgetting quotes around patterns with spaces or special characters.
FAQ
Yes: basic by default, -E for extended, -P for Perl syntax.
It searches trees you name; to find the commit that added text, use git log -S "text".