Understanding Hunk Headers in Unified Diffs
Deep dive into @@ hunk headers in unified diff format. Learn how line numbers and counts work, and what they mean for patch application.
Detailed Explanation
Anatomy of a Hunk Header
Every change section in a unified diff starts with a hunk header: @@ -oldStart,oldCount +newStart,newCount @@. This header tells the patch engine exactly where to apply changes.
Header Format
@@ -10,8 +10,12 @@ optional function context
| Component | Meaning |
|---|---|
-10,8 |
In the original file, this hunk starts at line 10 and spans 8 lines |
+10,12 |
In the new file, this hunk starts at line 10 and spans 12 lines |
optional text |
Some tools append the nearest function/class name for readability |
Counting Rules
The counts include all lines in the hunk body for their respective side:
- Context lines (
) count toward both old and new counts - Removed lines (
-) count toward the old count only - Added lines (
+) count toward the new count only
Example Verification
@@ -5,6 +5,8 @@
context line (old: 1, new: 1)
context line (old: 2, new: 2)
-removed line (old: 3)
-removed line (old: 4)
+added line (new: 3)
+added line (new: 4)
+added line (new: 5)
+added line (new: 6)
context line (old: 5, new: 7)
context line (old: 6, new: 8)
Old count: 2 context + 2 removed + 2 context = 6 . New count: 2 context + 4 added + 2 context = 8 .
Single-Line Shorthand
When a count is 1, it can be omitted: @@ -5 +5,2 @@ means the old side has 1 line starting at line 5, and the new side has 2 lines starting at line 5.
Use Case
You are debugging why a patch fails to apply. Understanding hunk headers helps you verify that line numbers and counts are correct, especially after manual edits to a patch file.