Git Diff: Compare Working Tree, Index and HEAD
Three states, one path
HEAD is the current recorded commit in this lab. The index is the proposed next snapshot. The working tree is the file you are editing. Start with Tea and Rice committed and Milk appended but unstaged. The arrows below describe data flow when staging and committing, not physical file copies.
The index can differ from both the working tree and the last commit.
Compare the right pair
Stage Milk, then append Bread without staging again. Now each state has different content. Use git diff to compare working tree against index, git diff --cached to compare index against HEAD, and git diff HEAD to compare tracked working contents against HEAD. The last command requires an existing HEAD; ordinary diffs do not include wholly untracked files.
git add -- notes.txtprintf 'Bread\n' >> notes.txtgit status --shortgit diff -- notes.txtgit diff --cached -- notes.txtgit diff HEAD -- notes.txtStatus is MM notes.txt. The first diff adds Bread, the cached diff adds Milk, and the HEAD diff adds both Milk and Bread. A plus at the start of a patch content line marks an addition; header lines such as +++ are not file content.
Commit only the staged part
Predict the new commit: it will contain Milk but not Bread. This is a safe way to separate related work without removing later edits. After checking, save the staged change and inspect both versions.
git commit -m "Add milk to notes"git show HEAD:notes.txtcat notes.txtgit status --shortThe committed file ends with Milk; the working file ends with Bread. Status is M notes.txt. Do not assume an empty staged diff means all work is saved. Practice: predict what the next commit would contain if you stage notes.txt again.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Git Diff: Compare Working Tree, Index and HEAD — knowledge check
Apply the lesson to common beginner repository states.
Which pair does plain git diff compare in the lab?
Which command compares the index with HEAD?
HEAD has Tea; index has Tea and Milk; disk has Tea, Milk and Bread. What does an ordinary commit record?
After that commit, which change remains unstaged?
Why does git diff HEAD fail before the first commit?