Skip to content

git grep — DevOps Search Patterns ​

git grep is the project-wide search tool for Git repositories. It skips .git directories, respects .gitignore, and can search any revision in history without checking it out. For a DevOps engineer that means: search production branches from a CI runner, audit staged changes before commit, or scan every tag for a leaked credential — all with one command and no checkout cost.

This guide covers everything git grep can do in a CI/CD context and the patterns that make it more useful than system grep for repo-native search.

Why git grep over system grep ​

Problemgrep -rgit grep
Searches .git/objects/ (noise + corruption risk)YesNo — skips .git automatically
Respects .gitignore and sparse-checkoutNo — must filter manuallyYes — built in
Search a specific revisionClone or git show | grepgit grep <pattern> <rev> — no checkout needed
Line numbers, column offsets-n works-n -c works
Binary file handlingGarbage outputSkips binaries by default
Threaded executionManual--threads N

Core flags for DevOps ​

Output control ​

git grep <pattern>                   # file:line match in working tree
git grep -n <pattern>                # add line number
git grep -c <pattern>                # add column offset (for GitHub/GitLab file annotations)
git grep --line-number <pattern>     # same as -n
git grep -o <pattern>                # show only matched text, not full line
git grep -l <pattern>                # file names only (CI gate: "did any file match?")
git grep -L <pattern>                # files that do NOT match (inverse -l)
git grep --count <pattern>           # match count per file (CI magnitude gate)
git grep -h <pattern>                # suppress filename (show only matched line)
git grep <pattern> <rev>                  # search at a fixed revision (no checkout)
git grep <pattern> <rev> -- <path>        # scoped to a subdirectory at that rev
git grep <pattern> <rev1> <rev2>          # multiple revisions
git grep <pattern> HEAD                   # last commit state (staged + committed)
git grep <pattern> HEAD^                  # parent commit state
git grep <pattern> v2.3.0                 # any tag
git grep <pattern> main..feature          # commits reachable from feature but not main

Revision-scoped search is the killer DevOps feature. You can audit every release tag for a secret without spinning up 50 worktrees:

for tag in $(git tag); do
  if git grep -q "API_KEY" "$tag" -- '*.py'; then
    echo "LAT?: $tag has API_KEY in Python files"
  fi
done

Scope: cached, untracked, no-index, worktree ​

git grep --cached <pattern>       # search staged content only
git grep --untracked <pattern>    # include untracked files
git grep --no-index <pattern>     # treat the directory as non-repo (system grep mode, but still skips .git)
git grep --no-exclude-standard    # include files normally ignored by .gitignore

--cached is useful for pre-commit hooks that want to scan only what's about to be committed:

# Pre-commit: reject any staged file containing a TODO
git grep --cached -l "TODO" && echo "REJECT: staged TODOs found" && exit 1

--untracked is useful for scanning newly generated artifacts that haven't been committed yet.

Boolean expressions ​

git grep --and -- -e <p1> -e <p2>          # lines matching both patterns
git grep --or  -- -e <p1> -e <p2>          # lines matching either pattern (default)
git grep --not -- -e <exclude>             # lines NOT matching the pattern
git grep --all-match -- -e <p1> -e <p2>    # files matching ALL patterns (not lines)
git grep -e <p1> --and -e <p2>             # same as --and

Use -- to separate git grep flags from patterns when mixing them:

# Files that reference both "TODO" and "security" (intersection, not union)
git grep --all-match -- -e TODO -e security

Real CI gate — find files with a hardcoded credential AND a URL pattern:

git grep --all-match -- -e "password" -e "https?://" -- '*.json'
if [ $? -eq 0 ]; then
  echo "REJECT: config files contain both credentials and URLs"
  exit 1
fi

Function context ​

git grep -p <pattern>     # show the function/class enclosing each match
git grep -W <pattern>     # show the whole function/class body containing each match

-p uses the same hunk-header rules as git diff (xfuncname from .gitattributes). For CI code review annotations, this locates the exact function a change touches:

# Before code review: every file matching "password" and the function it's in
git grep -pn password -- '*.py'

Formatting and grouping ​

git grep --break <pattern>       # blank line between file groups
git grep --heading <pattern>     # print file name as a heading before each group
git grep --color <pattern>       # ANSI color output (auto-detected by default)
git grep -v <pattern>            # invert match (show non-matching lines)
git grep -i <pattern>            # case-insensitive

Combine for code-review-friendly output:

git grep --break --heading -n -i "TODO\|FIXME\|HACK" src/

Parallel execution ​

git grep --threads <N> <pattern>

On multi-core CI runners, bump threads for large monorepos. Default is count of CPUs / 2. For a 32-core runner:

git grep --threads 16 -l "terraform" -- 'infra/**'

DevOps patterns ​

Pattern 1: Pre-commit secret scan ​

A lightweight pre-commit hook that rejects staged files with secrets:

bash
#!/bin/bash
# .git/hooks/pre-commit — secret scan
PATTERNS=("password\s*=" "api[_-]key\s*=" "secret\s*=" "token\s*=")
for p in "${PATTERNS[@]}"; do
  if git grep --cached -qI "$p"; then
    echo "REJECTED: staged files match pattern '$p'"
    echo "Affected files:"
    git grep --cached -lI "$p"
    exit 1
  fi
done

-I skips binary files so you don't get false positives from compiled artifacts.

Pattern 2: Release tag credential audit ​

Before a release, scan all tags for a leaked credential:

bash
#!/bin/bash
git tag --sort=-creatordate | head -20 | while read tag; do
  if git grep -q "AKIA[0-9A-Z]\{16\}" "$tag"; then
    echo "ALERT: AWS access key found in $tag"
    git grep -l "AKIA[0-9A-Z]\{16\}" "$tag"
  fi
done

Pattern 3: CI scope detection with --count ​

Determine whether a monorepo change touches infrastructure code:

bash
#!/bin/bash
# From a CI pipeline triggered on push
INFRA_COUNT=$(git grep --count "^resource\|^module\|^variable" HEAD^..HEAD -- 'infra/**' 2>/dev/null | wc -l)
APP_COUNT=$(git grep --count "func main\|func handle" HEAD^..HEAD -- 'app/**' 2>/dev/null | wc -l)

if [ "$INFRA_COUNT" -gt 0 ] && [ "$APP_COUNT" -gt 0 ]; then
  echo "matrix=[\"infra\",\"app\",\"tests\"]"  # run both pipelines
elif [ "$INFRA_COUNT" -gt 0 ]; then
  echo "matrix=[\"infra\",\"tests\"]"
elif [ "$APP_COUNT" -gt 0 ]; then
  echo "matrix=[\"app\",\"tests\"]"
fi

Note: This searches the diff range HEAD^..HEAD — the set of files changed in the last commit — not the working tree.

Pattern 4: CI gate with exit code ​

git grep -q exits 0 on match, 1 on no match. This makes it a pure CI gate:

bash
# Fail CI if any Go file imports a deprecated package
if git grep -q "old-deprecated-pkg" HEAD -- '*.go'; then
  echo "FAIL: deprecated imports found"
  exit 1
fi

# Warn but don't fail on debug log statements
if git grep -q "fmt.Println\|console.log" HEAD -- '*.go'; then
  echo "WARN: debug print statements in code — consider removing"
fi

Pattern 5: Branch divergence content audit ​

When a feature branch has drifted from main, audit what it brings that main doesn't have:

bash
# What does feature-branch have that main doesn't?
git grep -l "TODO\|FIXME" main..feature-branch

Or to find new functions introduced on a feature branch:

bash
git grep -pn "^func " main..feature-branch -- '*.go'

Pattern 6: Post-merge code metrics ​

After merging, report code density changes:

bash
#!/bin/bash
echo "=== Code metrics for merge ==="
echo "Total matches: $(git grep -c "func " HEAD -- '*.go' | awk -F: '{s+=$2}END{print s}')"
echo "Debug statements: $(git grep -c "fmt.Println\|log.Debug" HEAD -- '*.go' | awk -F: '{s+=$2}END{print s}')"
echo "Deprecated imports: $(git grep -c "old-deprecated-pkg" HEAD -- '*.go' | awk -F: '{s+=$2}END{print s}')"

In a sparse-checkout repo where most files aren't present in the working tree, git grep still searches only what's checked out. To search the full repo at a revision:

bash
# Search the full tree at HEAD (even files not checked out by sparse mode)
git grep <pattern> HEAD

# Search only checked-out paths (default git grep behavior)
git grep <pattern>

Pattern 8: Multi-revision diff-of-grep ​

Compare what tags contain a pattern:

bash
git grep -l "critical-feature" v1.0.0 v2.0.0 | sort | uniq

Or find files that lost a pattern between releases:

bash
HAD=$(git grep -l "deprecated-endpoint" v1.0.0 | sort)
HAS=$(git grep -l "deprecated-endpoint" v2.0.0 | sort)
echo "Removed from: $(comm -23 <(echo "$HAD") <(echo "$HAS"))"

Pattern 9: CI annotation with column offset ​

GitHub and GitLab file annotations accept line + column offsets. git grep -c outputs the column:

bash
git grep -cn "TODO\|FIXME" origin/main -- '*.rs'

Pipe this into an annotation formatter for CI:

bash
git grep -cn "TODO" origin/main -- '*.py' | while IFS=: read file line col match; do
  echo "::warning file=$file,line=$line,col=$col::TODO left in code"
done

Skip binaries with -I to avoid garbage output from compiled files:

bash
git grep -I -l "API_KEY" HEAD -- '*.py' '*.js' '*.go'

Or include binaries with -a (forces text treatment):

bash
git grep -a "version" HEAD -- '*.bin'

Performance notes ​

SetupTime (100K file monorepo)
grep -r "pattern" (includes .git)~2.1s
git grep "pattern" (working tree)~0.4s
git grep "pattern" HEAD (revision)~0.6s
git grep --threads 4 "pattern" HEAD~0.2s

git grep wins because it reads files from the object store when searching a revision (no filesystem read queuing) and walks only tracked files when searching the working tree.

Thread count: match to CPU count for CI runners. On shared runners, --threads 2 is usually sufficient.

Pitfalls ​

  1. Pattern is a regex, not a fixed string. git grep "file.txt" matches "file.txt" and "myfile.txt". Use git grep -F "file.txt" for fixed-string search.
  2. Shell expansion with glob patterns. git grep "pattern" -- *.py expands in the shell before reaching git grep. Use git grep "pattern" -- '*.py' with quotes to pass the glob to git itself.
  3. --cached only shows staged content. It does not show the working tree. To show both, leave off --cached.
  4. -q silences output but returns exit code. Use in CI gates to suppress match flooding.
  5. -l and -L are exclusive. Combine with -v to invert the match itself instead.
  6. Column offsets differ by shell. -c shows byte/character offset from line start. In CI annotation tools check whether they expect 0-indexed or 1-indexed columns. Git uses 1-indexed.
  7. Revision range grep is not the same as diff. git grep pattern A..B searches paths present at rev A AND at rev B. It does NOT search only the diff. For diff-scoped search, use git diff --name-only piped to git grep.

Git Master — Git Reference for Every Skill Level