Git Diff Comparison and Change Analysis

Comparing differences is an important tool for understanding code changes. By comparing the differences between different versions, you can clearly see what was changed, why it was changed, and the scope of the changes.

1. Basics of Comparing Differences

(1) The Three Areas of Git

Git has three important areas, and understanding them is key to mastering diffs:

100%
graph TB
    A[Workspace<br/>Working Directory] -->|git add| B[Buffer<br/>Staging Area]
    B -->|git commit| C[Repository<br/>Repository]
    
    A -.->|git diff| B
    B -.->|git diff --staged| C
    A -.->|git diff HEAD| C
    
    style A fill:#fff3cd
    style B fill:#d4edda
    style C fill:#c3e6cb

(2) Scenarios for Comparing Differences

(3) Overview of the diff Command

git diff Used to display differences. Basic usage:

BASH
git diff [options] [<commit>] [--] [<path>...]

2. Comparing the Three Regions

(1) Working Directory vs. Temporary Directory

Compare the differences between the working directory and the staging area—that is, unstaged changes.

▶ Example: Viewing Unstaged Changes

BASH
# Edit File
echo "new line" >> README.md

# View Workspace Changes(Relative to the temporary storage area)
git diff

# Output:
# diff --git a/README.md b/README.md
# index abc1234..def5678 100644
# --- a/README.md
# +++ b/README.md
# @@ -1,3 +1,4 @@
#  # My Project
#  
#  ## Features
# +new line

# View a Specific File
git diff README.md

# View Multiple Files
git diff file1.js file2.js

(2) Staging Area vs. Repository

Compare the differences between the staging area and the repository—that is, changes that have been staged but not yet committed.

▶ Example: View staged changes

BASH
# Add or modify to the staging area
git add README.md

# View changes in the staging area(Compared to the latest submission)
git diff --staged

# Or use the old syntax
git diff --cached

# Output:
# diff --git a/README.md b/README.md
# index abc1234..def5678 100644
# --- a/README.md
# +++ b/README.md
# @@ -1,3 +1,4 @@
#  # My Project
#  
#  ## Features
# +new line

(3) Working Directory vs. Repository

Compare the differences between the working directory and the repository—that is, all uncommitted changes.

▶ Example: View all unsaved changes

BASH
# View the workspace relative toHEADthe differences
git diff HEAD

# View the differences between the workspace and a specific commit
git diff a1b2c3d

# View the differences in the workspace compared to the last commit
git diff HEAD^

# The output includes all changes, both staged and unstaged.

3. Interpreting the Difference Output

(1) diff output format

▶ Example: Understanding diff Output

BASH
git diff

# Output Format Description:
# diff --git a/file.js b/file.js     <- GitDifferential Head
# index abc1234..def5678 100644      <- File Mode
# --- a/file.js                      <- Original Document(-Indicates deletion)
# +++ b/file.js                      <- New Document(+Indicates addition)
# @@ -1,3 +1,4 @@                     <- Change Location (hunk header)
#  # My Project                      <- Context Line(Starts with a space)
#  
#  ## Features                       <- Context Line
# +new line                          <- Add a row(+Introduction)
# -old line                          <- Delete Row(-Introduction)

(2) Hunk Header Format

hunk header format: @@ -a,b +c,d @@

TEXT
@@ -10,5 +10,7 @@ function login() {

This means that the 5 lines starting on line 10 of the original file have become 7 lines starting on line 10 of the new file.

(3) Statistical Information

▶ Example: Viewing a Summary of Statistics

BASH
# Display Statistics
git diff --stat

# Output:
#  README.md | 1 +
#  file1.js  | 5 ++---
#  file2.js  | 3 +++
#  3 files changed, 5 insertions(+), 3 deletions(-)

# Show brief statistics
git diff --shortstat

# Output:
# 3 files changed, 5 insertions(+), 3 deletions(-)

# Display Numerical Statistics
git diff --numstat

# Output:
# 1       0       README.md
# 2       3       file1.js
# 3       0       file2.js

4. Comparing Different Versions

(1) Compare the two commits

▶ Example: Submission Comparison

BASH
# Compare the two commits
git diff a1b2c3d d4e5f6g

# Compare a commit to the current workspace
git diff a1b2c3d

# Compare a commit to the staging area
git diff --staged a1b2c3d

# Compare Adjacent Commits
git diff HEAD^ HEAD

# View the changes introduced by a specific commit
git show a1b2c3d

# Equivalent to
git diff a1b2c3d^ a1b2c3d

(2) Compare Branches

▶ Example: Branch Comparison

BASH
# Compare Two Branches
git diff main feature

# ViewfeatureBranch relative tomainChanges to
git diff main...feature

# ViewmainBranch relative tofeatureChanges to
git diff feature...main

# Compare a specific file across branches
git diff main feature -- file.js

# View changes made after the branch was forked
git diff $(git merge-base main feature) feature

(3) Comparison Tags

▶ Example: Version Comparison

BASH
# Compare the Two Versions
git diff v1.0.0 v2.0.0

# View the changes in a specific version
git diff v1.0.0 HEAD

# View the release notes
git diff v1.0.0 v2.0.0 --stat

# Output:
#  src/auth.js   | 25 +++++++++++++++++++++++++
#  src/user.js   | 10 +++++-----
#  package.json  |  2 +-
#  3 files changed, 32 insertions(+), 5 deletions(-)

5. Detailed Explanation of the diff Option

(1) Common Options

Option Description Purpose
--staged Staging Area vs. Repository View Staged Changes
--stat View Statistics View and Edit Statistics
--shortstat Brief Statistics View Total Changes
--name-only Show filenames only View list of modified files
--name-status Display Status View File Modification Status
-w Ignore whitespace Ignore differences between spaces and tabs

▶ Example: Using the diff option

BASH
# Show only the names of modified files
git diff --name-only

# Output:
# README.md
# file1.js
# file2.js

# Display File Modification Status
git diff --name-status

# Output:
# M  README.md     <- Edit
# A  file1.js      <- New
# D  file2.js      <- Delete
# R  old.js new.js <- Rename

# Ignore differences in whitespace characters
git diff -w

# Ignore all spaces
git diff -w --ignore-blank-lines

# Show differences at the word level
git diff --word-diff

# Highlight in color
git diff --color-words

(2) Context Control

▶ Example: Controlling the Number of Lines in the Context

BASH
# Reduce the number of context lines
git diff -U1

# The output displays only1Line Context:
# @@ -10,3 +10,4 @@ function login() {
#   const user = authenticate();
# +  if (!user) return;
#   return user;

# Do not display context
git diff -U0

# Increase the number of context lines
git diff -U10

(3) Path Restrictions

▶ Example: Limiting the Comparison Range

BASH
# Compare only specific files
git diff -- file.js

# Compare only specific directories
git diff -- src/

# Exclude certain files
git diff -- . ':!*.test.js'

# Compare only a specific type of file
git diff -- '*.js'

6. Real-World Applications

(1) Pre-submission Check

▶ Example: Thoroughly check before submitting

BASH
# 1. View Uncommitted Changes
git diff

# 2. View Staged Changes
git diff --staged

# 3. View Statistics on All Changes
git diff HEAD --stat

# 4. Submit after verifying that everything is correct
git commit -m "feat: Add a New Feature"

(2) Code Review

▶ Example: Reviewing Someone Else's Code

BASH
# View the changes in a specific commit
git show a1b2c3d

# View statistics for a specific commit
git show --stat a1b2c3d

# View the list of files modified in a specific commit
git show --name-only a1b2c3d

# Compare the differences between the two branches
git diff main...feature

# ViewPull Requestthe differences
git diff origin/main...origin/feature

(3) Conflict Analysis

▶ Example: Analyzing Merge Conflicts

BASH
# View the content to be merged
git diff main...feature

# View common ancestors up tofeatureChanges to
git diff $(git merge-base main feature) feature

# View files that may be in conflict
git diff --name-only main...feature

# View the specific details of the conflict
git diff main feature -- file.js

(4) Confirmation of Version Rollback

▶ Example: Confirming the rollback content

BASH
# View content that would be lost if you undo the action
git diff HEAD HEAD~1

# View rollback statistics
git diff HEAD HEAD~1 --stat

# View the revision history for a specific file
git diff HEAD HEAD~1 -- file.js

# Execute the rollback after confirmation
git reset --hard HEAD~1

❓ FAQ

Q What is the difference between git diff, git diff --staged, and git diff HEAD?
A git diff Compare the working directory and the staging area (unstaged changes); git diff --staged Compare the staging area and the repository (staged changes); git diff HEAD Compare the working directory and the repository (all unsubmitted changes).
Q How can I view only the names of modified files without seeing their actual contents?
A Use git diff --name-only to display only the filenames, or use git diff --stat to display the filenames and modification statistics.
Q What do the "+" and "-" symbols in the diff output mean?
A Lines beginning with "+" indicate new content, lines beginning with "-" indicate deleted content, and lines beginning with a space are the original text (unchanged).
Q How do I compare the differences between two branches?
A Use git diff main feature to compare two branches, and use git diff main...feature to view the changes in the feature branch relative to the main branch (starting from the fork point).
Q How do I ignore differences in spacing?
A Use git diff -w to ignore differences between spaces and tabs, and use git diff --ignore-space-at-eol to ignore differences in trailing spaces.

📖 Summary


📝 Exercises

  1. Basic Exercise: Create a Git repository. After modifying a file, use git diff to view unstaged changes. After staging the changes, use git diff --staged to view staged changes.

  2. Advanced Exercise: Create two branches, make changes to the same file on different branches, use git diff to compare the differences between the two branches, and analyze the conflicts that may arise.

  3. Challenge: Use the various options of git diff (such as --stat, --name-status, -w, etc.) to analyze the changes made to a real-world project and generate a complete change report.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏