AI Hints
Home›Git & GitHub Tutorial›Practice: History Detective
Git & GitHub · Lesson 23 of 144

Comparing Two Commits

Git diff between commits.

⏱ 2 min read▶ Video at 23:55🎓 Free
Watch this lesson in the Git & GitHub courseWatch on YouTube ↗Full Git & GitHub course

Git diff isn't only for uncommitted changes. You can compare any two commits, to see everything that changed between them, across all files.

Comparing Two Commits
From the video: Comparing Two Commits
  • diff works between commits
  • Any two points in history
  • All files at once

Diff between two hashes

Git diff, then two hashes. The older one first, then the newer one. Here we compare the first commit with the latest. Dash dash stat gives a short summary of which files changed, and how much.

git
git diff --stat f7d9757 HEAD
 about.html | 2 ++
 index.html | 3 +++
 style.css  | 3 +++
 3 files changed, 8 insertions(+)

Using HEAD and tilde

Instead of hashes, you can count back from head. Head tilde two means two commits before head. So git diff head tilde two, head, shows everything from the last two commits. One line in the style file, and one on the home page.

git
git diff HEAD~2 HEAD
diff --git a/index.html b/index.html
index 93dd595..d4173c3 100644
--- a/index.html
+++ b/index.html
@@ -1,3 +1,4 @@
 <h1>My Site</h1>
 <p>Welcome!</p>
 <a href="about.html">About</a>
+<p>New: contact me anytime!</p>
diff --git a/style.css b/style.css
index 433e28e..a9b3d41 100644
--- a/style.css
+++ b/style.css
@@ -1,2 +1,3 @@
 body { font-family: sans-serif; }
 h1 { color: navy; }
+p { line-height: 1.6; }

Ways to name a commit

Here are the ways to point at a commit. A hash, or just its first seven characters. Head, the commit you're on. Head tilde one, its parent, and head tilde three, three commits back. And a branch name, which means the latest commit on that branch.

keyvalue
f7d9757a short hash
HEADwhere you are
HEAD~1, HEAD~31 or 3 commits back
mainthe tip of a branch

Summary

Git diff, with two commits, compares any two points in history. Head tilde N counts back from where you are. Next, the best part. Undoing mistakes.

Key takeaways
  • git diff <old> <new>
  • --stat for a summary
  • HEAD~N counts back
Next up: Throwing Away Changes — git restore