Git Diff: Compare Changes Between Commits and Branches
Learn how to use git diff to compare changes between commits, branches, and the working directory. Essential for code review workflows.
git diff main..feature-branchDetailed Explanation
What Does git diff Do?
git diff shows the differences between two states in your repository — whether that is the working directory vs. staging area, two commits, two branches, or specific files.
Common Patterns
# Unstaged changes (working directory vs. staging area)
git diff
# Staged changes (staging area vs. last commit)
git diff --staged
# Compare two branches
git diff main..feature-branch
# Compare a specific file between branches
git diff main..feature-branch -- src/app.tsx
# Compare two commits
git diff abc1234..def5678
Understanding the Output
--- a/src/app.tsx
+++ b/src/app.tsx
@@ -10,7 +10,7 @@
function App() {
- const count = 0;
+ const count = useState(0);
return <div>{count}</div>;
}
Lines prefixed with - were removed; lines with + were added. The @@ header shows the line numbers in the old and new versions.
Useful Flags
# Show only file names that changed
git diff --name-only main..feature
# Show file names with change type (Added, Modified, Deleted)
git diff --name-status main..feature
# Show word-level diffs instead of line-level
git diff --word-diff
# Ignore whitespace changes
git diff -w
# Show stats summary
git diff --stat main..feature
Diffing Against the Merge Base
To see what a branch introduced since it diverged from main:
git diff main...feature-branch # three dots
The triple-dot syntax compares feature-branch against the merge base (the common ancestor), which is usually what you want during code review. Mastering git diff is essential for understanding exactly what changed and why.
Use Case
Before submitting a pull request, a developer runs git diff main...feature to review all the changes introduced by their branch relative to the merge base.