Let’s take a look at the main purpose of and common uses for the git diff command.

First, here’s a quick summary (if you get the summary, reading the rest is optional):

# see the diference between 2 commits (i.e. which files were changed and how were they changed)
git diff <commit> <commit>

# see the difference between 2 commits but only for specific files
git diff <commit> <commit> -- <files>

# see the difference between 'working directory' and 'index'
git diff 

# see the difference between the 'working directory' and 'index' but only for certain files
git diff -- <files>

# see the difference between the index and HEAD
git diff --cached

# see the difference between the index and HEAD but only for certain files
git diff --cached -- <files>

# note, anytime when you want to limit the diff to certain files just add '-- <files>'

Overarching Purpose

The overarching purpose of git diff is to see the difference between two trees. A tree can be a commit, the index, or the working directory. You can see the difference between any 2 of these trees.

The most general syntax for using the command is as follows:

git diff <tree1> <tree2> -- <files>

This will show you the differences between the two trees that affect certain files (i.e. only shows how certain files changed from one tree to the other).

For example:

git diff 3ab456 9a3d56 -- '*.cpp' '.h'

Shows you how the .cpp and .h files changed between the commits 3ab456 9a3d56.

If you leave out the double dash part, you will see how all the files changed between the two commits. In other words, by adding the double dash, you are filtering the output to only show the differences between certain files (not all files).

Common Uses

To see all the difference between two commits:

git diff <commit1> <commit2>

To see how certain files changed between commits:

git diff <commit1> <commit2> -- <files>

To see the difference between the working directory and the index:

git diff

To only see how certain files changed (between working directory and the index)

git diff -- <files>

To see the difference between the index and HEAD

git diff --cached

To limit it to certain files:

git diff --cached -- <files>