By admin , 29 April 2026

Synopsis

git grep [<options>] <pattern> [<tree-ish>...]

Description

The git grep command searches files tracked by Git for a pattern. It is much faster than grep -r on large repositories because it only searches what Git knows about (skipping .git, build outputs, and ignored files) and uses Git's optimized object database. You can also search any historical revision or tree, not just the working copy.

Patterns can be plain strings, basic regex (default), extended regex (-E), or PCRE (-P if compiled in). Use git grep instead of grep -r in scripts that operate on Git repositories.

In day-to-day use, git grep integrates closely with shell aliases, editor plugins, and continuous integration. Power users often add aliases that combine flags they always pass, or wrap the command in scripts that enforce team conventions. Output formatting can be customized via Git config — pretty formats, color schemes, and pager behavior are all tunable. When something goes wrong, the first diagnostic step is usually to re-run the command with GIT_TRACE=1 in the environment, which reveals the underlying plumbing calls. For unusual situations, the --help output (git grep --help) opens the full manual page with details on every option, including those rarely used in casual workflows but essential for debugging or scripting at scale.

Understanding how git grep interacts with the rest of Git's data model — the object database, the index, refs, and the working tree — pays dividends. Each command operates on some subset of these pieces, and knowing which it touches helps predict outcomes and recover from mistakes. Reading the official Git documentation alongside hands-on practice in a throwaway repository is the fastest way to internalize the nuances. Most production issues with Git stem from one of three causes: surprising default behavior, partial network operations, or rewriting history that was already shared. A working mental model of git grep's side effects helps avoid all three.

Common Options

OptionDescription
-iCase-insensitive match.
-nShow line numbers.
-lList only matching file names.
-EExtended regular expressions.
-PPerl-compatible regex.
-wMatch whole words.
--cachedSearch the index instead of the working tree.
--untrackedAlso search untracked, non-ignored files.

Examples

git grep "TODO"
# Find every TODO in tracked files

git grep -n -i "deprecated" src/
# Case-insensitive, with line numbers, under src/

git grep "fooBar" v1.0.0
# Search the v1.0.0 tag's tree

git grep -E "^(import|from) " --and -e "json"
# Combined patterns: lines starting with import/from that mention json

Common Mistakes

Forgetting that git grep only searches tracked files — newly added files won't appear unless staged or you pass --untracked. PCRE features (\b, lookbehind) require Git built with PCRE support and the -P flag.

Related Commands

git log -S, git log -G, git ls-files, git show