Unified Diff Format for Patch Files and Version Control

Understand the unified diff format used by Git, patch files, and version control systems. Learn the syntax of hunks, context lines, and the --- / +++ header notation used in .diff and .patch files.

Basic Diff

Detailed Explanation

Unified Diff Format

The unified diff format is the standard output format for git diff, diff -u, and patch files. It combines both versions into a single stream with line prefixes indicating additions (+), deletions (-), and unchanged context lines (space).

Anatomy of a Unified Diff

--- a/config.json
+++ b/config.json
@@ -5,7 +5,8 @@
   "debug": false,
   "port": 3000,
-  "host": "localhost",
+  "host": "0.0.0.0",
+  "cors": true,
   "timeout": 30
 }

Header Lines

  • --- a/file — the original file path
  • +++ b/file — the modified file path
  • @@ -5,7 +5,8 @@ — the hunk header indicating line ranges: starting at line 5 with 7 lines in the original, and starting at line 5 with 8 lines in the modified

Line Prefixes

Each line in a hunk is prefixed with exactly one character:

Prefix Meaning
(space) Context — unchanged line shown for reference
- Deletion — line removed from original
+ Addition — line added in modified version

Context Lines

By default, git diff shows 3 context lines around each change. Context lines help readers understand where the change occurs within the file. You can adjust this with git diff -U<n> where n is the number of context lines.

Multiple Hunks

A single file diff can contain multiple hunks when changes occur in different parts of the file. Each hunk has its own @@ header and is separated by context lines.

Reading Hunk Headers

The hunk header @@ -10,4 +10,6 @@ means:

  • Original: starts at line 10, spans 4 lines
  • Modified: starts at line 10, spans 6 lines (2 lines were added)

Use Case

Unified diff format is essential for Git workflows. Developers encounter it when running git diff, reviewing patches via email, applying changes with git apply, and reading CI/CD pipeline outputs. Understanding this format is crucial for anyone working with version control, contributing to open source projects, or troubleshooting merge conflicts.

Try It — Diff Viewer

Open full tool