git-grep
Search files for matching text patterns
TLDR
Search for a string in files in the current HEAD
Search for a string in files matching a glob pattern in the current HEAD
Search for a string, including submodules
Search for a string at a specific point in history
Search for a string across all branches and all of history
SYNOPSIS
git grep [options] <pattern> [<pathspec>…]
PARAMETERS
-i, --ignore-case
Ignore case distinctions in pattern and files.
-v, --invert-match
Select non-matching lines.
-n, --line-number
Prefix output with line numbers.
-l, --files-with-matches
Only show filenames with matches.
-L, --files-without-match
Only show filenames without matches.
-c, --count
Show count of matching lines per file.
-q, --quiet
Suppress all output; exit with status.
--cached
Search files in the index instead of worktree.
--no-index
Search files in directory tree, ignoring Git.
-a, --text
Process binary files as text.
-F, --fixed-strings
Interpret pattern as fixed string.
-P, --perl-regexp
Use Perl-compatible regex.
-e pattern
Specify pattern explicitly.
--all-match
All paths must match all patterns.
-O file
Open matching files in pager/editor.
--break
Add breaks between results per file.
-A num, --after-context
Show num lines after match.
-B num, --before-context
Show num lines before match.
-C num, --context
Show num lines before/after match.
DESCRIPTION
git grep is a powerful search tool built into Git for finding patterns in tracked files within a repository. It leverages Git's index and object database for speed, making it far more efficient than plain grep on large repositories.
Unlike standard grep, which scans the filesystem sequentially, git grep can search the Git index (--cached), the working tree, or both simultaneously. It automatically skips untracked files and respects .gitignore patterns unless overridden. Supports full grep-style regex (PCRE with -P), fixed strings (-F), context lines (-A, -B, -C), and Git-specific features like searching across submodules or limiting depth.
Output includes filename, line number, and matching line by default, with options to suppress details (-q, -l). Ideal for code review, debugging, or locating strings in version-controlled projects. Use pathspecs to narrow scope, e.g., git grep pattern *.py.
CAVEATS
Skips untracked files and binaries by default; use --no-index or -a to override. Limited to repository contents unless --no-index. Not for searching commit history (use git log -G).
EXIT STATUS
0 if matches found, 1 if none, 2 on error.
PATHSPECS
Supports Git pathspecs like **:*.c for recursive globbing.
HISTORY
Introduced in Git 1.0.13 (February 2006) as a Perl script (git-grep.pl), rewritten in C by 2007 for performance. Evolved with Git, adding PCRE support (v1.9, 2014) and submodule recursion.


