git grep

Debugging

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>...]
[ ] optional| or<arg> placeholder... repeatable--flag option

Options

Click any option to expand

Beginner (5)

Prefix each match with its line number.

RecommendedJump straight to the matching line

Example

git grep -n cart

Ignore differences between upper and lower case.

RecommendedFind a word however it is capitalized

Example

git grep -i welcome

Show the number of matching lines per file instead of the lines.

When neededHow many lines match in each file

Example

git grep -c cart

Show only the names of files that contain a match.

When neededList which files match, e.g. to open them all

Example

git grep -l login

Match the pattern only as a whole word.

When neededAvoid partial-word matches

Example

git grep -w i

Choosing the Right Option

git grep vs grep

Why use Git’s own search

CommandSearchesOld versions
grep -rEvery file on disk, including node_modulesNo
git grepOnly tracked filesYes: 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.0

Search the project as it was at v1.0.


Only some files

git grep "TODO" -- "*.js"

Limit the search to JavaScript files.

Workflow Examples

1
git grep -n "count("

Every call with its line

2
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

A:

Yes: basic by default, -E for extended, -P for Perl syntax.

A:

It searches trees you name; to find the commit that added text, use git log -S "text".