How to show diff between commits in Git?

To show the difference between commits, you use git diff. There are two ways of finding the differences:

  1. Using HEAD pointer
  2. Using commit-SHAs

How to show diff between commits using HEAD pointer?

HEAD is a pointer that always points to the most recent commit. It is always written in capital letters. Here, you specify the position of a commit from HEAD. Let's understand the entire concept with the help of an example:

To get a list of commits along with their commit-SHAs, run the following command:

$git log --oneline
7ad5e0e Updated Second line
e0d605d Added second line
9c18895 Added first line
5f968ea Initial commit

In the above example, HEAD is pointing to 7ad5e0e. Now, you want to show the difference between HEAD and e0d605d. e0d605d is at the first position from HEAD, so command will be:

$git diff HEAD~1
diff --git a/index.html b/index.html
index c18576a..a9425b5 100644
--- a/index.html
+++ b/index.html
@@ -1,2 +1,2 @@
 <p>First paragraph.</p>
-<p>Second paragraph.</p>
+<p>Third paragraph.</p>

Suppose you want to show the difference between HEAD and 5f968ea. 5f968ea is at the third position from HEAD, so the command to show the difference is

$git diff HEAD~3
diff --git a/index.html b/index.html
index c18576a..a9425b5 100644
--- a/index.html
+++ b/index.html
@@ -1,2 +1,2 @@
+<p>First paragraph.</p>
+<p>Third paragraph.</p>

So, the syntax to show the difference between commits using HEAD pointer is

$git diff HEAD~number

number is the position of the commit from HEAD pointer.

How to show diff between commits using commit-SHAs?

When you want to show the difference between two commits, you have to specify commits' SHAs. In that case, the syntax will be different and is shown below:

$git diff earlier-commit-SHAs later-commit-SHAs

Let's understand the meaning of later-commit-SHAs and earlier-commit-SHAs.

$git log --oneline
7ad5e0e Updated Second line
e0d605d Added second line
9c18895 Added first line
5f968ea Initial commit

Now, suppose you want to find the difference between e0d605d and 5f968ea. You can see that commit 5f968ea happened before commit e0d605d. So, 5f968ea is the earlier-commit-SHAs and e0d605d is the later-commit-SHAs. The command will be:

$git diff 5f968ea e0d605d
diff --git a/index.html b/index.html
index e69de29..c18576a 100644
--- a/index.html
+++ b/index.html
@@ -0,0 +1,2 @@
+<p>First paragraph.</p>
+<p>Second paragraph.</p>