Skip to content

Git patch-id: Stable Patch Identity for DevOps ​

git patch-id computes a SHA-1 checksum of a diff that stays stable across cherry-picks, rebases, amends, and most whitespace changes. Two commits that apply the same logical change produce the same patch-id, even when their commit SHA, author, date, message, and line numbers differ.

It's the engine behind git cherry (which detects unpicked commits across branches) and the closest Git has to a content-addressable identity for a change itself, independent of where or when it was applied.

Why a DevOps Engineer Needs This ​

ProblemWithout patch-idWith patch-id
Backport was applied but you need to prove itManually diff the patches, compare hunksgit show <original> | git patch-id == git show <backport> | git patch-id
CI merged a hotfix; now the feature branch contains the same fix — will it conflict?Guess, or do a test mergegit cherry reports patch-equivalent commits as already applied
A colleague cherry-picked your fix but changed the message — is it the same change?Read both diffs, comparepatch-id matches regardless of message or author
Security patch CVE-2024-xxx was backported to 3 release branches — verify all three are identicalSide-by-side diff of each backportOne pipeline: compute patch-id on each branch, assert all match
A rebase changed your commit SHA — did any hunks change?git range-diff (requires old/new ranges)git show HEAD | git patch-id — if the id matches the original, the change is identical

How It Works ​

git patch-id reads a diff from stdin and outputs:

<PATCH_ID> <COMMIT_SHA>

The patch-id is computed from the diff content only — specifically the hunks, file modes, and the index line's blob SHAs (not line numbers). The commit metadata (author, date, message, parent SHAs) is completely excluded.

Stable vs Unstable Mode ​

Git 2.37+ has two modes:

git patch-id --stable    # default — includes blob SHAs from index lines
git patch-id --unstable  # legacy — excludes index lines

--stable is the default and should always be used. Two commits that apply the same logical change produce the same stable patch-id even when:

  • Line numbers differ (hunks shifted by unrelated changes)
  • Whitespace context differs
  • Commit message, author, date differ
  • The commit is on a different branch

--unstable is only needed when interoperating with scripts written before Git 2.37.

What patch-id includes ​

  • File mode changes (new mode, old mode)
  • The "index" line's blob SHAs (in stable mode) — this means two files with identical content but different blob hashes produce different patch-ids
  • Added and removed lines in each hunk
  • File header paths (the --- a/ and +++ b/ lines)

What patch-id excludes ​

  • Commit SHA
  • Author name, email, date
  • Committer name, email, date
  • Commit message
  • Parent commit SHAs
  • Line numbers in hunk headers (@@ -10,7 +10,7 @@ vs @@ -15,7 +15,7 @@)
  • Number of context lines
  • Trailing whitespace on context lines

Basic Usage ​

bash
# Compute patch-id for a single commit
git show HEAD | git patch-id

# Output: <40-char-hex> <commit-sha>
# e.g.: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0 abc123def456...

# Compute patch-id for a range
git log --patch v1.0..v2.0 | git patch-id

# Check if a specific commit matches another
git show <SHA1> | git patch-id
git show <SHA2> | git patch-id
# Compare the first field (patch-id) — if equal, the changes are identical

Single-commit shorthand ​

Since patch-id outputs both the patch-id and the commit SHA, you can extract just the id:

bash
git show HEAD | git patch-id | cut -d' ' -f1

Comparing multiple commits in one pass ​

git patch-id outputs one line per commit it finds in the diff stream. Pipe a log range:

bash
# List all commits in a range with their patch-ids
git log --patch --format="commit %H" HEAD~5..HEAD | git patch-id

# Output:
# a1b2c3... <SHA1>
# d4e5f6... <SHA2>
# g7h8i9... <SHA3>

DevOps Patterns ​

Pattern 1: Backport Fidelity Gate ​

A CI pipeline that verifies a backport commit is patch-equivalent to the original:

bash
#!/bin/bash
# verify-backport.sh — assert backport is identical to original
set -euo pipefail

ORIGINAL_SHA="$1"   # commit on main or release branch
BACKPORT_SHA="$2"    # claimed backport commit

ORIG_ID=$(git show "$ORIGINAL_SHA" | git patch-id | cut -d' ' -f1)
BACKPORT_ID=$(git show "$BACKPORT_SHA" | git patch-id | cut -d' ' -f1)

if [ "$ORIG_ID" = "$BACKPORT_ID" ]; then
  echo "PASS: Backport is patch-equivalent to original ($ORIG_ID)"
  exit 0
else
  echo "FAIL: Backport patch-id ($BACKPORT_ID) differs from original ($ORIG_ID)"
  echo "Original: $ORIGINAL_SHA"
  echo "Backport: $BACKPORT_SHA"
  exit 1
fi

CI workflow integration:

yaml
# .forgejo/workflows/backport-verify.yaml (or GitHub Actions)
backport-verify:
  steps:
    - run: |
        ORIG=$(git log --oneline --all --grep="(#1234)" | head -1 | cut -d' ' -f1)
        BPT=$(git rev-parse HEAD)
        bash scripts/verify-backport.sh "$ORIG" "$BPT"

Pattern 2: CI Gate — Reject Duplicate Fixes ​

A pre-merge gate that detects if the incoming branch contains a fix that was already applied to the target branch. This prevents merge conflicts from duplicate cherry-picks and ensures idempotent patch application.

bash
#!/bin/bash
# gate-duplicate-patch.sh — fail if any commit in HEAD has a patch-equivalent on target
set -euo pipefail

TARGET="${1:-origin/main}"

# Get patch-ids for all commits on target (recent history, e.g. last 500)
TARGET_IDS=$(mktemp)
git log --patch --format="commit %H" "$TARGET"~500.."$TARGET" | git patch-id | cut -d' ' -f1 | sort > "$TARGET_IDS"

# Get patch-ids for all commits on current branch (not on target)
CURRENT_IDS=$(mktemp)
git log --patch --format="commit %H" "$TARGET..HEAD" | git patch-id | cut -d' ' -f1 | sort > "$CURRENT_IDS"

# Check for overlap
DUPLICATES=$(comm -12 "$TARGET_IDS" "$CURRENT_IDS")

if [ -n "$DUPLICATES" ]; then
  echo "FAIL: Found patch-equivalent commits already on $TARGET"
  echo "$DUPLICATES" | while read -r pid; do
    echo "  Duplicate patch-id: $pid"
    echo "  On target: $(grep "$pid" "$TARGET_IDS")"
    echo "  In branch: $(grep "$pid" "$CURRENT_IDS")"
  done
  rm -f "$TARGET_IDS" "$CURRENT_IDS"
  exit 1
fi

echo "PASS: No duplicate patches detected"
rm -f "$TARGET_IDS" "$CURRENT_IDS"

Pattern 3: Cross-Branch Cherry-Pick Audit with git cherry ​

git cherry is a porcelain wrapper around patch-id. It finds commits in one branch that are missing from another, using patch-equivalence:

bash
# Find commits in HEAD that are NOT patch-equivalent to anything on main
git cherry -v main HEAD

# Output:
# + abc1234 feat: add rate limiting          # not on main
# - def5678 fix: correct timeout handling    # patch-equivalent to a commit on main
# + 7890abc refactor: extract auth module    # not on main

The + prefix means "not yet applied to main." The - prefix means "patch-equivalent to a commit already on main" — i.e., this commit's change already exists there, even if the SHA and message differ.

DevOps pattern — backport coverage report:

bash
#!/bin/bash
# backport-coverage.sh — report which fixes from a release branch are missing from another
set -euo pipefail

SOURCE_BRANCH="${1:-origin/release/v2.1}"
TARGET_BRANCH="${2:-origin/release/v2.0}"

echo "=== Backport coverage: $SOURCE_BRANCH → $TARGET_BRANCH ==="

# Commits in source that are not patch-equivalent on target
git cherry -v "$TARGET_BRANCH" "$SOURCE_BRANCH" | grep '^+' | while read -r _ sha msg; do
  echo "  MISSING: $sha — $msg"
done

echo ""
echo "=== Already backported (patch-equivalent) ==="
git cherry -v "$TARGET_BRANCH" "$SOURCE_BRANCH" | grep '^-' | while read -r _ sha msg; do
  echo "  BACKPORTED: $sha — $msg"
done

Pattern 4: Post-Rebase Integrity Check ​

After an interactive rebase, verify that no commits were accidentally dropped or corrupted:

bash
#!/bin/bash
# rebase-integrity.sh — verify patch-ids survived a rebase
set -euo pipefail

ORIG_BASE="$1"   # commit before rebase (from ORIG_HEAD or reflog)

echo "=== Patch-id comparison: pre-rebase vs post-rebase ==="

# Capture patch-ids before rebase
PRE=$(mktemp)
git log --patch --format="commit %H" "$ORIG_BASE"..ORIG_HEAD | git patch-id | sort > "$PRE"

# Capture patch-ids after rebase
POST=$(mktemp)
git log --patch --format="commit %H" "$ORIG_BASE"..HEAD | git patch-id | sort > "$POST"

# Compare
MISSING=$(comm -23 "$PRE" "$POST")
NEW=$(comm -13 "$PRE" "$POST")

if [ -z "$MISSING" ] && [ -z "$NEW" ]; then
  echo "PASS: All commits survived rebase with identical patches"
elif [ -n "$MISSING" ]; then
  echo "WARNING: Commits missing after rebase (dropped or changed):"
  echo "$MISSING"
fi
if [ -n "$NEW" ]; then
  echo "INFO: New commits present after rebase:"
  echo "$NEW"
fi

rm -f "$PRE" "$POST"

Pattern 5: Security Patch Consistency Across Release Branches ​

When a CVE fix must land on multiple active release trains, verify every branch has the identical fix:

bash
#!/bin/bash
# verify-cve-backports.sh — assert all release branches carry the same security fix
set -euo pipefail

CVE_SHA="$1"     # the canonical fix commit (e.g., on main)
shift
BRANCHES=("$@")  # release branches to check (e.g., v2.1 v2.0 v1.9)

CANON_ID=$(git show "$CVE_SHA" | git patch-id | cut -d' ' -f1)
echo "Canonical patch-id: $CANON_ID (from $CVE_SHA)"

FAILED=0
for BRANCH in "${BRANCHES[@]}"; do
  # Find the commit on this branch with the same patch-id
  BRANCH_ID=$(git show "$BRANCH:patch" 2>/dev/null | git patch-id | cut -d' ' -f1 || echo "")

  # Or search the branch's log for a matching patch-id
  BRANCH_SHA=$(git log --patch --format="commit %H" "$BRANCH" | git patch-id | grep "^$CANON_ID" | head -1 | cut -d' ' -f2)

  if [ -n "$BRANCH_SHA" ]; then
    echo "  OK   $BRANCH — patch-id match at $BRANCH_SHA"
  else
    echo "  FAIL $BRANCH — no patch-equivalent commit found"
    FAILED=1
  fi
done

exit $FAILED

Pattern 6: Pre-Merge Gate — No Surprise Patch Duplication ​

A CI check that runs before merging a PR to ensure the incoming changes don't duplicate fixes already on the target branch. Useful when multiple engineers independently fix the same issue.

bash
#!/bin/bash
# pre-merge-patch-gate.sh
set -euo pipefail

TARGET_BRANCH="origin/${GITHUB_BASE_REF:-main}"

# Fetch target if needed
git fetch origin "$GITHUB_BASE_REF" 2>/dev/null || true

# Get patch-ids for commits unique to this branch
BRANCH_IDS=$(git log --patch --format="commit %H" "$TARGET_BRANCH..HEAD" | git patch-id | cut -d' ' -f1)

# Check each against target's recent history
for pid in $BRANCH_IDS; do
  if git log --patch --format="commit %H" "$TARGET_BRANCH"~200.."$TARGET_BRANCH" | git patch-id | grep -q "^$pid"; then
    echo "FAIL: Patch $pid exists on target branch already"
    exit 1
  fi
done

echo "PASS: No duplicate patches"

Script: patch-id-manage.sh ​

See scripts/patch-id-manage.sh for an automation utility that wraps these patterns into reusable subcommands: id, cherry, backport-verify, gate-duplicates, rebase-integrity, cve-consistency, pre-merge-gate, and diff-range.

patch-id vs range-diff ​

Both commands compare changes, but they serve different purposes:

Aspectgit patch-idgit range-diff
What it comparesOne commit vs one commit (via stable hash)Two ranges of commits (old side vs new side)
OutputSingle hash per commitSide-by-side diff of each paired commit
GranularityPer-commit identityPer-hunk difference
Tells you"Are these two changes the same?""What exactly changed between these two ranges?"
Use caseBackport verification, duplicate detection, CI gatesRebase review, force-push audit, PR diff review
False positivesVery low (identical diff content)None (shows actual diff)
PerformanceFast (SHA-1 of diff stream)Slower (full patch comparison)

Use patch-id when you only need a yes/no answer about patch equivalence. Use range-diff when you need to understand what changed between two related ranges.

Pitfalls ​

1. patch-id is not commit identity ​

Two commits with the same patch-id are not the same commit. They are patch-equivalent: the logical change is identical. The commit message, author, date, and parent history may differ entirely.

2. File rename changes patch-id ​

If a file is renamed between the original and the backport, the --- a/ and +++ b/ paths in the diff change, producing a different patch-id. To handle renames, use --find-renames with diff:

bash
git show --find-renames=<SHA> | git patch-id

3. Binary file changes ​

git patch-id works on textual diffs only. Binary file changes produce no diff hunks and therefore no useful patch-id. For binary files, rely on git range-diff or blob SHA comparison (git rev-parse <SHA1>:<path> <SHA2>:<path>).

4. Stable vs unstable mismatch ​

If two environments use different Git versions (pre-2.37 vs post-2.37), --stable mode may produce different patch-ids for the same diff. Always use --stable explicitly, and ensure all CI runners are on Git 2.37+.

bash
# Explicit stable mode (safe even on older Git that only has unstable)
git show HEAD | git patch-id --stable

On Git < 2.37, --stable is not recognized and the command falls back to --unstable. Pin Git versions across runners, or detect and handle the mismatch:

bash
if git patch-id --stable </dev/null 2>/dev/null; then
  PATCH_ID_CMD="git patch-id --stable"
else
  PATCH_ID_CMD="git patch-id"  # legacy unstable mode
fi

5. Large diff streams ​

Piping git log --patch across thousands of commits into git patch-id is memory-intensive. For large-scale audits, batch by range:

bash
# Process in chunks of 500 commits
for range in $(git rev-list --count main~2000..main | xargs -I{} seq 1 500 {}); do
  git log --patch --format="commit %H" main~"$((range+500))"..main~"$((range))" | git patch-id
done

6. Empty diffs ​

A merge commit or a commit with no file changes produces an empty diff stream, and git patch-id outputs nothing. Filter these out before piping:

bash
git log --patch --diff-filter=ACMRT --format="commit %H" main..HEAD | git patch-id

7. Combined diff format for merges ​

git show on a merge commit outputs a combined diff by default, which git patch-id may not handle correctly. Use -m to expand merges into individual diffs against each parent:

bash
git show -m <MERGE_SHA> | git patch-id

Reference ​

bash
# Get patch-id for current commit
git show HEAD | git patch-id --stable

# Get patch-id for a specific commit
git show <SHA> | git patch-id --stable

# List all commits in a range with their patch-ids
git log --patch --format="commit %H" <range> | git patch-id --stable

# Find commits on branch that are NOT on main (patch-equivalent)
git cherry -v main HEAD

# Count patch-equivalent commits between branches
git cherry main HEAD | grep '^-' | wc -l

# Check if a specific commit is already applied to another branch
git log --patch --format="commit %H" <branch> | git patch-id --stable | grep "$(git show <SHA> | git patch-id --stable | cut -d' ' -f1)"

# Verify all commits in a backport range are patch-equivalent to originals
git log --patch --format="commit %H" <orig-range> | git patch-id --stable > /tmp/orig-ids
git log --patch --format="commit %H" <backport-range> | git patch-id --stable > /tmp/backport-ids
diff /tmp/orig-ids /tmp/backport-ids

See Also ​

  • docs/devops-workflows/git-cherry-pick.md — selective commit backport patterns
  • docs/devops-workflows/git-range-diff.md — comparing commit ranges after rebase
  • docs/devops-workflows/git-rebase-interactive.md — interactive rebase operations
  • docs/recipes/patch-id-quick.md — one-page cheat sheet
  • scripts/patch-id-manage.sh — automation utility

Git Master — Git Reference for Every Skill Level