Comparing Changes with git diff (Working Tree vs Staged vs HEAD)
Comparing Changes with git diff (Working Tree vs Staged vs HEAD)
Before staging or committing code, careful developers verify their exact modifications. The git diff command is Git's microscope: it shows line-by-line additions, deletions, and alterations using unified diff format.
1. The Three Forms of git diff
Because Git has three trees (Working Directory, Staging Area, and HEAD Commit), git diff provides three primary comparison targets:
1. git diff (Working Directory vs. Staging Area)
Shows changes you have made in files that have NOT yet been staged:
2. git diff --staged (Staging Area vs. Last Commit)
Shows changes that are currently staged and ready to be included in the next commit:
3. git diff HEAD (Working Directory vs. Last Commit)
Shows all changes on your disk (both staged and unstaged combined) compared against the last recorded commit:
2. Reading Unified Diff Syntax
When you run git diff, Git outputs unified diff notation:
Decoding the Diff:
--- a/src/app.py: Original version before changes (pre-image).+++ b/src/app.py: Modified version after changes (post-image).@@ -10,7 +10,8 @@: Hunk header. In the original file, chunk begins at line 10 and spans 7 lines; in the new file, chunk begins at line 10 and spans 8 lines.-(Red) : Removed / deleted lines.+(Green) : Added / inserted lines.- White / uncolored text : Unchanged context lines around the modification.
3. Targeted Diffs
Compare a Specific File:
Compare Two Different Branches:
See what changes exist in feature-login compared to main:
Compare Two Commits by Hash:
Word-Level Diff (--word-diff):
When you change only one word inside a long paragraph, viewing the entire line as deleted and re-added can be noisy:
Practice Quiz
git diff without any arguments compare?+ signify?git diff HEAD display?dev and main?Ignoring Unwanted Files and Secrets using .gitignore Rules
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.