1. Home
  2. Blog
  3. DevOps

DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame shows, for every line of a file, the commit and author that last changed it. Plain blame is often wrong about the person who matters, because reformatting and moving code rewrite history on the surface. We built a four-commit repository and used -w, -L, -C and an ignore-revs file to trace each line back to the change that actually introduced it.

9 min read
Git blame explained: find who changed a line, and why

Key takeaways

  • Git blame lists the last commit to touch each line, which after a reformat is usually the reformat, not the real author.
  • -w ignored the whitespace-only commit and correctly credited the discount logic to its author, Ben.
  • Default -C missed a function moved to another file because it was under 40 characters; -C20 found it.
  • A .git-blame-ignore-revs file skips formatting commits for everyone, and git log -S finds the commit that added a value.

A line of code looks wrong. Before you change it, you want to know why it is there: who wrote it, in which commit, and with what explanation. Git blame answers that by annotating every line with the commit that last modified it. Then you read the commit message, the linked ticket or the pull request, and decide with context instead of guessing.

We ran every command on Git 2.56.0 in a small repository built for this article, with sample authors and example.com addresses.

What git blame shows

git blame shop.py
^b4a5f0a (Asha Dev 2026-09-01 10:00:00 +0000 1) def price(qty, unit):

Each line shows the abbreviated commit hash, author, date, line number and content. A leading ^ marks the boundary commit, here the first commit in the repository. Blame reports the last change to each line, which is the crucial detail: if someone later reindented, renamed or moved a line, they become its “author” in plain blame.

Our test repository

git log --oneline
3950a0a Move tax into ship.py               (Dara)
084c7fe Reformat to 4-space indent          (Chen)
98da12c Bulk discount for 10+ items         (Ben)
b4a5f0a Add price and tax                   (Asha)

Asha wrote price() and tax(). Ben added a bulk discount. Chen changed the indentation from two spaces to four across the whole file, a typical formatter commit. Dara moved tax() into a new file, ship.py. That history contains the two things that fool blame most often: reformatting and moving code.

Basic blame: the reformat hides everyone

git blame shop.py
^b4a5f0a (Asha Dev 2026-09-01 ... 1) def price(qty, unit):
084c7feb (Chen Fmt 2026-11-01 ... 2)     total = qty * unit
084c7feb (Chen Fmt 2026-11-01 ... 3)     if qty >= 10:
084c7feb (Chen Fmt 2026-11-01 ... 4)         total = total * 0.9
084c7feb (Chen Fmt 2026-11-01 ... 5)     return total

Every indented line was blamed on Chen’s reformat. Only the first line, which had no indentation to change, still pointed at Asha. If you wanted to ask about the 10 percent discount on line 4, plain blame sends you to the wrong person.

-w: ignore whitespace changes

git blame -w shop.py
^b4a5f0a (Asha Dev 2026-09-01 ... 1) def price(qty, unit):
^b4a5f0a (Asha Dev 2026-09-01 ... 2)     total = qty * unit
98da12c1 (Ben Ops  2026-10-05 ... 3)     if qty >= 10:
98da12c1 (Ben Ops  2026-10-05 ... 4)         total = total * 0.9
^b4a5f0a (Asha Dev 2026-09-01 ... 5)     return total

With -w, Git ignores whitespace when matching lines to their previous versions, so the indentation-only commit no longer counts. The discount lines now correctly point at Ben’s commit, and the rest back at Asha. Use -w by default; there is rarely a reason not to.

-L: blame a line range or a function

git blame -s -L 3,4 shop.py
084c7fe 3)     if qty >= 10:
084c7fe 4)         total = total * 0.9

git blame -s -w -L :price shop.py
^b4a5f0a 1) def price(qty, unit):
^b4a5f0a 2)     total = qty * unit
98da12c1 3)     if qty >= 10:
98da12c1 4)         total = total * 0.9
^b4a5f0a 5)     return total

-L 3,4 limits output to lines 3 and 4, which is much faster on large files. -L :price finds the function named price and blames just its body, so you do not need line numbers that change with every edit. You can repeat -L for several ranges. -s hides the author and date columns for compact output.

Ignoring reformat commits permanently

git log --format=%H --grep=Reformat > .git-blame-ignore-revs
git blame -s --ignore-revs-file .git-blame-ignore-revs shop.py
^b4a5f0a 1) def price(qty, unit):
^b4a5f0a 2)     total = qty * unit
98da12c1 3)     if qty >= 10:
98da12c1 4)         total = total * 0.9
^b4a5f0a 5)     return total

-w only helps with whitespace. Formatters also change quotes, line wrapping and trailing commas. A file listing commit hashes to ignore, conventionally named .git-blame-ignore-revs and committed to the repository, tells blame to look straight through those commits. Set git config blame.ignoreRevsFile .git-blame-ignore-revs so it applies automatically, or use --ignore-rev HASH for one-off cases. GitHub’s blame view reads a file with exactly this name in the repository root.

Tip: when you introduce a code formatter, make the reformat a single commit containing nothing else, then immediately add its hash to .git-blame-ignore-revs.

Marking lines affected by ignored commits

git -c blame.markIgnoredLines=true blame -s --ignore-revs-file .git-blame-ignore-revs shop.py
^b4a5f0a1 1) def price(qty, unit):
^?b4a5f0a 2)     total = qty * unit
?98da12c1 3)     if qty >= 10:
?98da12c1 4)         total = total * 0.9
^?b4a5f0a 5)     return total

Ignoring a commit means Git has to guess which earlier commit a line came from. With blame.markIgnoredLines, lines whose attribution passed through an ignored commit get a ?, so you know the answer is inferred. A related setting, blame.markUnblamableLines, marks lines added by the ignored commit itself with *.

-C: follow code moved between files

git blame -s ship.py              # and the same with -C
3950a0a 4) def tax(total):
3950a0a 5)     rate = 0.18
3950a0a 6)     return round(total * rate, 2)

git blame -s -C20 ship.py
^b4a5f0a shop.py 4) def tax(total):
084c7feb shop.py 5)     rate = 0.18
084c7feb shop.py 6)     return round(total * rate, 2)

git blame -s -w -C20 --ignore-revs-file .git-blame-ignore-revs ship.py
^b4a5f0a shop.py 4) def tax(total):
^b4a5f0a shop.py 5)     rate = 0.18
^b4a5f0a shop.py 6)     return round(total * rate, 2)

Moving tax() into ship.py made Dara the apparent author of all of it. -C tells blame to look for lines copied or moved from other files changed in the same commit, but our first attempts with -C and even -w -C -C still showed Dara. The reason is a threshold: Git only treats a block as moved if it contains at least 40 alphanumeric characters, and our three-line function had fewer. -C20 lowered the threshold, and blame then showed the original file name and commits. Combined with -w and the ignore file, every line traced back to Asha’s original commit. Repeating the option (-C -C, or three times) widens the search to more commits and files at the cost of speed; -M does the same for lines moved within one file.

Script-friendly output

git blame -w --line-porcelain -L 4,4 shop.py | grep -E "^(author |author-mail|summary)"
author Ben Ops
author-mail <ben@example.com>
summary Bulk discount for 10+ items

--line-porcelain prints full commit details for every line in a stable, parseable format: author, email, timestamps and the commit summary. Use it in scripts, for example to list the owners of a file or to find who to ask about lines touched by a failing test. When the fix belongs on another branch, git cherry-pick moves the relevant commit across.

Beyond blame: git log -L and git log -S

git log --oneline -L 3,4:shop.py
084c7fe Reformat to 4-space indent
98da12c Bulk discount for 10+ items
b4a5f0a Add price and tax

git log --oneline -S "0.9"
98da12c Bulk discount for 10+ items

Blame shows only the latest change per line. git log -L 3,4:file shows the whole history of a line range, every commit that touched it, with diffs. git log -S "text" (the pickaxe) finds commits that added or removed a string, which answers “when did this magic number first appear?” in one command. Our git log guide covers more of these options.

Blame in editors and on GitHub

Most editors show blame inline (in VS Code through extensions such as GitLens), and GitHub, GitLab and Bitbucket have a blame view with a button to step back to the previous revision of a line. GitHub honours .git-blame-ignore-revs. These views are faster for exploring; the command line is better for -C, line ranges and scripts.

Blame without blaming

The name is unfortunate. Use git blame to find context, not culprits: the author may have had constraints you cannot see, and the commit message or linked review usually explains them. Teams that use blame to shame people get vaguer commit messages and fewer small, honest commits. Good habits make blame useful: descriptive commit messages, ticket references, separate commits for formatting, reverting rather than rewriting shared history (see git reset vs revert), and squash or rebase choices that keep history readable, as discussed in our merge vs rebase guide.

Git blame cheat sheet

Goal Command
Blame a file, ignoring whitespace git blame -w file
Only some lines git blame -L 10,20 file
Only a function git blame -L :name file
Follow moved or copied code git blame -w -C20 file
Skip formatting commits git config blame.ignoreRevsFile .git-blame-ignore-revs
Blame an older version git blame v1.2 -- file
Full history of lines git log -L 10,20:file
When a string appeared git log -S "text"

For everyday commands beyond blame, keep our Git commands cheat sheet handy, and use git worktree to check out an old version next to your current one while investigating.

Final thoughts

Plain git blame answers “who touched this line last”, which after a formatter run or a file move is rarely the question you care about. Add -w every time, keep a .git-blame-ignore-revs file for formatting commits, use -C (with a lower threshold for small blocks) when code has moved, and switch to git log -L or -S when you need the full story. In our repository, those options turned four misleading attributions into the right author for every line.

Frequently asked questions

What does git blame do?

It shows, for each line of a file, the commit, author and date of the last change to that line, so you can find the commit and message that explain why the code looks the way it does.

How do I ignore whitespace changes in git blame?

Add the w option. Git then ignores whitespace when matching lines to earlier versions, so indentation-only commits are skipped.

How do I ignore a formatting commit in git blame?

List its hash in a file named .git-blame-ignore-revs, commit the file, and set blame.ignoreRevsFile to that file name. Blame then looks through those commits.

Why does git blame not follow code I moved to another file?

Use the C option. If the moved block is short, also lower the threshold, for example C20, because by default Git ignores blocks with fewer than 40 alphanumeric characters.

How do I see the whole history of a line, not just the last change?

Use git log with the L option and a line range and file, such as 10,20:file. It lists every commit that changed those lines, with diffs.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Confusion Matrix Explained: Precision, Recall, F1 and Thresholds in Python

Confusion matrix explained with Python: TP, FP, FN, TN, precision, recall, F1, the accuracy trap, threshold choice by cost and…

Read article →
Software Development

API Pagination: Offset vs Cursor vs Keyset, Tested on 1 Million Rows

API pagination explained: offset vs keyset and cursor pagination timed on 1 million rows, duplicates when data changes, the ties…

Read article →
DevOps

Git Submodule Explained: Add, Clone, Update and Remove Safely

Git submodule explained: add, clone, update –init, update –remote, the detached HEAD trap, foreach and clean removal, tested step by…

Read article →
Test Automation

Pytest tmp path Explained: tmp_path, tmp_path_factory and Temp Files

Pytest tmp_path explained: per-test temporary folders, tmp_path_factory for shared files, monkeypatch.chdir, legacy tmpdir, retention and basetemp.

Read article →
Software Testing

Test Case Prioritization: 6 Techniques Compared With APFD

Test case prioritization compared: risk, coverage, cost, history and random orders scored with APFD and time to find all faults…

Read article →
Databases & SQL

Full Text Search in SQL: FTS5, Ranking, Phrases and Speed

Full text search in SQL with SQLite FTS5: MATCH queries, phrases, prefixes, NEAR, stemming, BM25 ranking, snippets, two gotchas and…

Read article →
Databases & SQL

Generated Columns in SQL: Virtual vs Stored, Indexes and Limits

Generated columns in SQL explained: virtual vs stored, automatic updates, write errors, storage cost, indexing, JSON fields and support in…

Read article →
Software Development

Object Freeze in JavaScript: Shallow vs Deep, Seal and const

Object freeze in JavaScript explained: freeze vs seal vs const, strict mode errors, shallow vs deep freeze, frozen arrays, Map…

Read article →
Software Development

Python hashlib: SHA-256, File Hashes, HMAC and Password Hashing

Python hashlib explained: SHA-256 for strings and files, algorithm speeds, why passwords need PBKDF2 or scrypt, safe verification and HMAC…

Read article →
Software Development

Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys

Python UUID explained: uuid4, uuid5, uuid1 privacy, time-ordered uuid7, parsing, storage formats and UUIDs as database keys, tested on Python…

Read article →
Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →