git grep
Search for text patterns across tracked files in your repository, faster and more Git-aware than regular grep.
You need to find where a specific function is called across your entire
codebase, or search for a configuration variable that might appear in several
files. git grep searches through files tracked by Git, finding patterns much
faster than standard grep because it only searches tracked files and leverages
Git's internal data structures.
Running git grep "searchPattern" searches for the pattern in all tracked files
in your working directory. It shows matching lines with the filename and line
number, making it easy to locate results. Unlike regular grep, it automatically
ignores untracked files, build artifacts, and anything in .gitignore, focusing
on actual source code.
Adding -n shows line numbers, which is often default in many configurations.
The -i flag makes the search case-insensitive: git grep -i "TODO" finds
"todo," "TODO," and "ToDo." The -w flag matches whole words only:
git grep -w "log" finds "log" but not "login" or "dialog."
You can search in specific paths or files: git grep "pattern" -- src/ searches
only in the src directory. To search in a specific commit or branch, add the
reference: git grep "pattern" main searches in the main branch, while
git grep "pattern" abc123 searches in a specific commit.
The -c flag counts matches per file instead of showing lines:
git grep -c "TODO" shows how many TODOs exist in each file. The -l flag
lists only filenames with matches, without showing the matching lines
themselves.
For more advanced searches, -E enables extended regular expressions:
git grep -E "function\s+\w+" finds function declarations. The --and, --or,
and --not flags let you combine patterns:
git grep --all-match -e pattern1 -e pattern2 finds lines matching both
patterns.
In pull request workflows, git grep helps reviewers understand how code is used across the codebase. If a PR modifies a utility function, you can grep for its usage to see what might be affected. This is faster than IDE search in large repositories and works on servers or in CI environments without a full IDE setup.
Understanding git grep means having a fast, Git-aware search tool that respects your repository structure and ignores noise. It's optimized for finding code, making it the right tool for locating functions, variables, TODOs, or any text pattern in your source files.
