The git diff
command is a powerful tool that helps developers see changes in their code—what’s been added, removed, or modified—before committing or after merging. Whether you’re reviewing your own work or troubleshooting a conflict, understanding how to use git diff
effectively can boost your productivity and confidence in Git.
In this guide, we’ll walk through how to use git diff
in different scenarios with practical examples.
🧠 What is git diff
?
git diff
shows you the line-by-line differences between two sets of files in your Git repository. It can compare:
- Your working directory with the staging area
- The staging area with the last commit
- Any two commits or branches
🔍 Common git diff
Use Cases
1. See Changes Not Yet Staged
git diff
This shows the difference between your working directory and the staging area. In other words, it tells you what you’ve changed but not yet staged.
2. See Staged Changes
git diff --cached
or
git diff --staged
This shows the changes that are staged for the next commit, compared to the last commit.
3. Compare Working Directory with Last Commit
git diff HEAD
This shows all changes (both staged and unstaged) since the last commit.
🔁 Compare Branches or Commits
4. Compare Two Branches
git diff main..feature-branch
Shows changes in feature-branch
that are not in main
.
Add --name-only
to list changed files:
git diff main..feature-branch --name-only
5. Compare Two Commits
git diff <commit1> <commit2>
Example:
git diff a1b2c3d e4f5g6h
This shows what changed between two specific commits.
📁 Compare Specific Files or Directories
6. Check Differences in a Specific File
git diff path/to/file.py
7. Check Differences in a Directory
git diff src/
This helps you focus on a subset of your project.
🧰 Useful Options and Flags
Option | Description |
---|---|
--color | Forces colored output (useful in some terminals) |
--stat | Shows a summary of changes (files, insertions) |
--name-only | Lists only the names of changed files |
--word-diff | Shows changes word-by-word instead of line-by-line |
--unified=0 | Reduces surrounding context lines (good for small diffs) |
Example:
git diff --stat
📘 Summary of Common Commands
Task | Command |
---|---|
Show unstaged changes | git diff |
Show staged changes | git diff --cached |
Compare branches | git diff branch1..branch2 |
Compare commits | git diff <commit1> <commit2> |
Show file-level changes only | git diff --name-only |
Get summary of changes | git diff --stat |
🧠 Tip: Use Visual Git Tools
While git diff
is great in the terminal, tools like VS Code, GitKraken, or GitHub Desktop offer visual diffs, which can be easier to read for complex changes.
🧩 Conclusion
Whether you’re doing code reviews, prepping for a commit, or troubleshooting a bug, git diff
is your go-to command for understanding changes in your project. With a little practice, you’ll find it invaluable for keeping your code clean, accurate, and review-ready.