git diff — Comparing Changes
The git diff command shows exactly what changed between two states. It's essential for reviewing your work before committing.
Three Types of Diff
Working Dir → git diff → Staging Area → git diff --staged → Last Commit
git diff— Shows unstaged changes (working dir vs. index)git diff --staged— Shows staged changes (index vs. HEAD)git diff HEAD— Shows all changes (working dir vs. HEAD)
Reading Diff Output
--- a/file.txt
+++ b/file.txt
@@ -1,3 +1,3 @@
line one
-old line two
+new line two
line three
- Lines starting with
-were removed - Lines starting with
+were added - Lines without prefix are context (unchanged)
Try it!
Practice seeing diffs at each stage:
- Create and commit a file:
echo "hello" > file.txt && git add file.txt && git commit -m "Add file" - Modify the file:
echo "hello world" > file.txt - See unstaged changes:
git diff - Stage the change:
git add file.txt - See staged changes:
git diff --staged
Notice how git diff shows nothing after staging (changes moved from working dir to index), but git diff --staged now shows the change.
Key Insight
Always run git diff --staged before committing to verify exactly what will be included. This prevents accidental commits of debug code or incomplete changes.