Sub topic 8
Seeing what changed with git diff
This chapter assumes you have a repository with at least one commit, know how git add stages a file, and understand the three areas: working tree, staging area, and repository. Here you will learn how git diff compares those areas, so you can check a change before you commit it.
What git diff compares
git diff shows line-level differences between two states. Which two states depends on the options you give it.
| Command | Compares | Answers the question |
|---|---|---|
| `git diff` | Working tree vs. staging area | What have I changed but not yet staged? |
| `git diff --staged` | Staging area vs. last commit | What will my next commit contain? |
--cached is a synonym for --staged.
Worked example
Start in a repository where README.md is already committed. Append a line, then compare at each step.
echo "More details." >> README.md
git diff
git add README.md
git diff
git diff --stagedThe first git diff prints the change. The working tree differs from the staging area, because the staging area still holds the old version.
After git add, the second git diff prints nothing. The working tree and the staging area now match. Empty output here does not mean the change is lost. The change has moved to the next area.
git diff --staged now shows the change, because the staging area differs from the last commit.
Reading the output
A diff for the example looks like this:
diff --git a/README.md b/README.md
index 1a2b3c4..5d6e7f8 100644
--- a/README.md
+++ b/README.md
@@ -1 +1,2 @@
# Hello Git
+More details.--- a/README.mdis the old version and+++ b/README.mdis the new version.@@ -1 +1,2 @@is a hunk header. It says the hunk covers line 1 of the old file and lines 1 to 2 of the new file.- Lines starting with
+were added, lines starting with-were removed, and lines starting with a space are unchanged context.
Your index hashes will differ.
Common errors
- Empty
git diffaftergit add. The change is staged. Rungit diff --stagedto see it. - Untracked files do not appear. A new file that you have never staged is not in the staging area or the last commit, so plain
git diffignores it. Usegit statusto find it. Aftergit add, it shows up ingit diff --staged. - Partly staged files. If you stage a file and then edit it again, both commands show output.
git diff --stagedshows what was staged, andgit diffshows only the edits made after that.
Useful variations
git diff README.mdlimits the output to one path.git diff --statprints a summary of changed files and line counts instead of the full diff.
Exercise
You edit notes.txt, run git add notes.txt, and then run git diff. It prints nothing. Which command shows your change, and why was the first output empty?
Show answer
git diff --staged shows it. Plain git diff compares the working tree with the staging area, and after git add those two are identical, so there is nothing to print. The change now differs from the last commit, which is what --staged compares.