elefcode
← All guides

Dev Basics · 4 min read

How Diffs Work: Reading Unified Diff Output

Every pull request, git diff, and patch file uses the same unified diff format. Learning to read it fluently makes code review faster and merge conflicts less scary.

Try it yourself with the related tool.

Compare two files →

Advertisement

The anatomy of a unified diff

The header lines --- a/file and +++ b/file name the old and new versions. Each change is a hunk starting with a line like @@ -12,7 +12,8 @@: the old file's hunk starts at line 12 and spans 7 lines; the new one starts at line 12 and spans 8. Inside, lines beginning with - were removed, + were added, and a space marks unchanged context.

How the changes are found

A diff algorithm looks for the longest common subsequence — the largest set of lines that appear in both versions in the same order — and reports everything else as removed or added. Git uses the Myers algorithm by default. The "patience" and "histogram" variants anchor on unique lines and often produce more readable diffs for moved code.

Why a small edit can look big

Diffs work on whole lines, so changing one word shows the entire line as removed and re-added. Reformatting, changed indentation, or Windows versus Unix line endings can turn every line into a change. Use git diff -w to ignore whitespace, or a word-level view to see exactly which characters changed.

Reviewing more effectively

Side-by-side views are easier for edits; unified views are better for additions. Keep formatting changes in a separate commit from logic changes, so reviewers are not hunting for the real change among hundreds of reformatted lines.

Related guides