This post will discuss how to find differences between two arbitrary commits in Git.

The git diff command is commonly used to get the unstaged changes between the index and working directory. It can be also used to show changes between two arbitrary commits.

git diff <commit-id> <commit-id>

To view the changes between two commits, you can provide the commit hashes. The hash can be a full SHA-1 hash or a short SHA-1 hash or ancestry path.

For instance, the following command will list out all the changes made in the last commit. Here, HEAD represents the current branch’s tip, and HEAD^ represents the version before the last commit.

git diff HEAD^ HEAD

The following is synonymous with the above syntax.

git diff HEAD^..HEAD

The advantage of using this version is that we can omit either commit here, and it will have the same effect as using HEAD instead. The following will compare with the tip of the current branch by default.

git diff HEAD^..
Limit comparison to specified file:

The following will compare with the tip of the current branch but limit the comparison to the specified file.

git diff HEAD^ HEAD -- ./file
Generate output to a file:

To generate output to a .diff file instead of stdout, you can use the --output option:

git diff HEAD^ HEAD --output=patch.diff

You can also redirect the output to a file:

git diff HEAD^ HEAD > patch.diff
List only names of changed files:

If you only need the names and status of changed files, you can use the --name-status option. The common statuses are Added (A), Copied (C), Deleted (D), Modified (M), Renamed (R).

git diff HEAD~5 HEAD --name-status

Here, the HEAD~5 refers to the last 5 commits.

 
git diff name-status option

 
Alternatively, you can use the --stat or --compact-summary option to generate a diffstat.

git diff HEAD~5 HEAD --compact-summary

git diff compact-summary option

That’s all about finding the differences between two Git commits.