Comparing versions¶
git show displays the changes introduced by one commit. To compare any two versions of a file (the version you are editing, the staged version, or two past commits), use git diff.
What git diff compares¶
Each form of git diff compares two of the places a file can live:
flowchart LR
wd["Working directory"]
idx["Staging area"]
head[("Last commit<br/>HEAD")]
old[("An earlier commit")]
idx <-- "git diff" --> wd
head <-- "git diff --staged" --> idx
old <-- "git diff <older> <newer>" --> head
| Command | Compares |
|---|---|
git diff |
The staging area with the working directory: changes not yet staged |
git diff --staged |
The last commit with the staging area: changes staged for the next commit |
git diff <commit> <commit> |
Two commits |
Add a file name to any of them to restrict the comparison to that file, for example git diff README.md.
When nothing is staged, the staging area contains the same thing as the last commit, so git diff simply shows everything you changed since the last commit. Once you stage part of your changes, git diff no longer shows that part: use git diff --staged for it (git diff documentation).
Comparing to an unstaged file¶
In the homelab repository, README.md was edited after the last commit, and not staged. One to-do item was reworded and a new one was added:
$ git diff README.md
diff --git a/README.md b/README.md
index 7ad4d7a..f0b262f 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,4 @@
# Homelab
-TODO: describe the network layout.
+TODO: draw the network diagram.
TODO: schedule weekly backups.
+TODO: renew the domain name.
Reading the output¶
| Line | Meaning |
|---|---|
diff --git a/README.md b/README.md |
The file being compared. Version a is the older one (here the staged version, identical to the last commit). Version b is the newer one (here the working directory). |
index 7ad4d7a..f0b262f 100644 |
Short hashes of the two blobs (old..new), and the file mode (100644, a regular file) |
--- a/README.md |
Lines from version a are marked with - |
+++ b/README.md |
Lines from version b are marked with + |
@@ -1,3 +1,4 @@ |
Hunk header: where the changes are. -1,3 means "starting at line 1, 3 lines of version a"; +1,4 means "starting at line 1, 4 lines of version b". |
# Homelab |
A line starting with a space is unchanged (context) |
-TODO: describe the network layout. |
A line starting with - was removed (shown in red in a colour terminal) |
+TODO: draw the network diagram. |
A line starting with + was added (shown in green) |
A modified line appears as one removed line followed by one added line, as with the network to-do item. The section grew from 3 to 4 lines because one line was also added at the end.
Comparing to a staged file¶
After git add, the change is in the staging area, so plain git diff shows nothing:
$ git add README.md
$ git diff
$ git diff --staged
diff --git a/README.md b/README.md
index 7ad4d7a..f0b262f 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,4 @@
# Homelab
-TODO: describe the network layout.
+TODO: draw the network diagram.
TODO: schedule weekly backups.
+TODO: renew the domain name.
The output format is identical; only the two versions compared change. git diff --staged is a good check just before git commit: it shows exactly what the commit will record. --cached is a synonym of --staged.
Comparing two commits¶
- Find the commit hashes with
git log --oneline. - Pass both hashes to
git diff, older commit first:
$ git diff 2553c7d dd032b5
diff --git a/inventory.csv b/inventory.csv
index 1fb1eb9..59c3965 100644
--- a/inventory.csv
+++ b/inventory.csv
@@ -1,2 +1,3 @@
hostname,ip,role
pi-dns,192.168.1.10,dns
+nas,192.168.1.20,storage
diff --git a/services.md b/services.md
new file mode 100644
index 0000000..6f0ce8d
--- /dev/null
+++ b/services.md
@@ -0,0 +1,4 @@
+# Services
+
+- Pi-hole on pi-dns
+- Samba shares on nas
The output contains one section per changed file:
- In
inventory.csv, the hunk went from 2 to 3 lines: the NAS was added. services.mddid not exist in the first commit. Git shows it as anew file, compared with/dev/null(nothing), and every line is an addition. Itsindexline starts with0000000for the same reason.
Using HEAD instead of hashes¶
HEAD refers to the latest commit of the current branch. Instead of looking up hashes, you can count back from it with ~:
flowchart RL
h["420feb7<br/>Add media server<br/><b>HEAD</b>"] --> h1["cdf805a<br/>Add web server…<br/><b>HEAD~1</b>"]
h1 --> h2["dd032b5<br/>Add NAS…<br/><b>HEAD~2</b>"]
h2 --> h3["2553c7d<br/>Create README…<br/><b>HEAD~3</b>"]
HEAD~n means "go back n parents from HEAD". To see the changes introduced by the most recent commit, compare it with its parent:
$ git diff HEAD~1 HEAD
diff --git a/inventory.csv b/inventory.csv
index a695d1c..00b6c38 100644
--- a/inventory.csv
+++ b/inventory.csv
@@ -2,3 +2,4 @@ hostname,ip,role
pi-dns,192.168.1.10,dns
nas,192.168.1.20,storage
pi-web,192.168.1.30,web
+192.168.1.40,media,mediabox
Order matters
git diff always describes how to go from the first version to the second. With the older commit first, additions appear with +, as in history. If you swap them (git diff HEAD HEAD~1), the result is reversed: the line added by the commit appears with -. Always write the older version first.
Summary¶
| Command | Function |
|---|---|
git diff |
Changes in all files that are not staged (staging area vs working directory) |
git diff README.md |
Same, for one file |
git diff --staged |
Changes in all staged files compared with the latest commit |
git diff --staged README.md |
Same, for one file |
git diff 2553c7d dd032b5 |
Changes between two commits, using hashes (older first) |
git diff HEAD~1 HEAD |
Changes between two commits, using HEAD references |
Hands-on labs¶
Three labs, from guided to more autonomous. Each one has its own setup, so you can do them in any order and repeat them as often as you like. Type the commands rather than pasting them, and read every output before moving on: the goal is to build reflexes, not to reach the end.
Lab 1: compare versions at every stage¶
Objective: use git diff to compare the working directory, the staging area, and past commits, and interpret the output.
Prerequisites and initial state: Git installed. The setup creates ~/git-practice/diff with a README in three commits.
Setup:
mkdir -p ~/git-practice/diff && cd ~/git-practice/diff
git init -q -b main
git config user.name "Practice User"
git config user.email "[email protected]"
printf '# Homelab\nTODO: describe the network layout.\n' > README.md
git add . && git commit -q -m "Create README"
echo "TODO: schedule weekly backups." >> README.md
git commit -q -am "Add backup reminder"
echo "TODO: set up monitoring." >> README.md
git commit -q -am "Add monitoring reminder"
Tip
git commit -am "..." stages every already-tracked modified file and commits in one step. It is used here only to build the history quickly; it does not add untracked files.
Tasks:
- Replace the line
TODO: describe the network layout.withTODO: draw the network diagram.inREADME.md(with an editor orsed), without staging it. Show the change withgit diff. - Stage the file. What does
git diffshow now? Which command shows the staged change? - Without using hashes, show the change introduced by the most recent commit.
- Show all changes between the first commit and the most recent commit, using
HEADreferences. - Run
git diff HEAD HEAD~2, then compare its+/-signs with those of task 4.
Expected result and verification:
- One line starting with
-TODO: describe the network layout.and one line starting with+TODO: draw the network diagram.. git diffprints nothing, whilegit diff --stagedprints the same diff as in task 1.- A single added line:
+TODO: set up monitoring.. - Two added lines: the backup and monitoring reminders.
- The same two lines, but with
-instead of+.
Solution
# 1. Unstaged change
sed -i 's/TODO: describe the network layout./TODO: draw the network diagram./' README.md
git diff # staging area vs working directory
# 2. Staged change
git add README.md
git diff # empty: nothing is left unstaged
git diff --staged # last commit vs staging area
# 3. Changes introduced by the latest commit
git diff HEAD~1 HEAD
# 4. From the first commit to the latest one
git diff HEAD~2 HEAD
# 5. Reversed order
git diff HEAD HEAD~2
- After
git add, the change moves from "unstaged" to "staged". This is why plaingit diffbecomes empty and--stagedis needed. - The repository has three commits, so the first one is
HEAD~2. - Swapping the two references reverses the meaning of the diff: additions appear as deletions. Put the older version first.
- Tasks 3 to 5 compare commits, so the staged change from task 2 does not appear in them.
Clean up when you are done: rm -rf ~/git-practice/diff.
Lab 2: predict, then check¶
Objective: know, without running anything, what git diff and git diff --staged will show at each step of the add/commit workflow.
Prerequisites and initial state: Git installed. The setup creates ~/git-practice/predict with one committed file.
Setup:
mkdir -p ~/git-practice/predict && cd ~/git-practice/predict
git init -q -b main
git config user.name "Practice User"
git config user.email "[email protected]"
printf '# Services\n- pi-dns: Pi-hole\n' > services.md
git add . && git commit -q -m "Create services list"
Tasks: after each step, write down your prediction for git diff and git diff --staged (empty, or which line), then run both commands to check.
- Add the line
- nas: Samba sharestoservices.md. - Stage
services.md. - Add another line,
- web01: Nginx. - Commit with the message
Add NAS service. - Stage and commit the remaining change with the message
Add web service.
Expected result and verification:
| After step | git diff |
git diff --staged |
|---|---|---|
| 1 | +- nas: Samba shares |
empty |
| 2 | empty | +- nas: Samba shares |
| 3 | +- web01: Nginx |
+- nas: Samba shares |
| 4 | +- web01: Nginx |
empty |
| 5 | empty | empty |
Solution
echo "- nas: Samba shares" >> services.md
git diff; git diff --staged # 1. unstaged NAS line / nothing
git add services.md
git diff; git diff --staged # 2. nothing / staged NAS line
echo "- web01: Nginx" >> services.md
git diff; git diff --staged # 3. web line / NAS line
git commit -m "Add NAS service"
git diff; git diff --staged # 4. web line / nothing
git add services.md
git commit -m "Add web service"
git diff; git diff --staged # 5. nothing / nothing
git diffanswers "what wouldgit addadd?", andgit diff --stagedanswers "what wouldgit commitrecord?".- At step 3, the same file has a different change on each side: the NAS line is staged, the web line is not.
- When both commands print nothing, the working directory, the staging area, and the last commit are identical:
git statussaysworking tree clean.
Clean up when you are done: rm -rf ~/git-practice/predict.
Lab 3: spot the change¶
Objective: find when and how a value changed, by comparing commits and restricting a diff to one file.
Prerequisites and initial state: Git installed. The setup creates ~/git-practice/spot with four commits. Somewhere along the way, the NAS changed address.
Setup:
mkdir -p ~/git-practice/spot && cd ~/git-practice/spot
git init -q -b main
git config user.name "Practice User"
git config user.email "[email protected]"
printf '# Homelab\n' > README.md
printf 'hostname,ip,role\npi-dns,192.168.1.10,dns\nnas,192.168.1.20,storage\n' > inventory.csv
git add . && git commit -q -m "Create homelab notes"
echo "web01,192.168.1.30,web" >> inventory.csv
echo "TODO: schedule weekly backups." >> README.md
git commit -q -am "Add web server and backup reminder"
sed -i 's/192.168.1.20/192.168.1.25/' inventory.csv
git commit -q -am "Reorganise addresses"
echo "TODO: set up monitoring." >> README.md
git commit -q -am "Add monitoring reminder"
Tasks:
- Show the changes made by the most recent commit, without using a hash.
- Show the changes made to
README.mdsince the very first commit. - Show only the changes made to
inventory.csvby the second commit (Add web server and backup reminder). - Find, by comparing pairs of consecutive commits, which commit changed the address of the NAS.
- Copy the hashes of the first and the last commits from
git log --oneline, and compare them. - Bonus: run the comparison of task 5 again with
--stat. What does this option summarise?
Expected result and verification:
- One added line:
+TODO: set up monitoring.. - Two added lines: the backup and monitoring reminders.
- One added line:
+web01,192.168.1.30,web, and nothing aboutREADME.md. git diff HEAD~2 HEAD~1shows-nas,192.168.1.20,storageand+nas,192.168.1.25,storage: the commit isReorganise addresses.- Changes in both files: three lines added in total, one removed.
README.md | 2 ++,inventory.csv | 3 ++-, and2 files changed, 4 insertions(+), 1 deletion(-).
Solution
# 1. Latest commit
git diff HEAD~1 HEAD
# 2. One file, since the first commit (four commits: the first one is HEAD~3)
git diff HEAD~3 HEAD README.md
# 3. One file, one commit: compare it with its parent
git diff HEAD~3 HEAD~2 inventory.csv
# 4. Walk through consecutive pairs
git diff HEAD~3 HEAD~2 inventory.csv # web01 added, NAS unchanged
git diff HEAD~2 HEAD~1 inventory.csv # here: .20 becomes .25
# 5. With hashes, older first
git log --oneline
git diff 3c4d5e6 7a8b9c0 # replace with your own hashes
# 6. Summary per file
git diff --stat 3c4d5e6 7a8b9c0
- A file path at the end of
git diffrestricts the output to that file, exactly as withgit log. - "The changes made by commit X" always means "the difference between X and the commit just before it".
--statcounts the changed lines per file: a modified line counts as one insertion and one deletion, as in the commit output.- The history page gives a faster way for task 4:
git log --oneline inventory.csv, thengit showon each candidate.
Clean up when you are done: rm -rf ~/git-practice/spot.