0
0
GitHow-ToBeginner · 3 min read

How to Compare Commits in Git: Simple Commands and Examples

To compare commits in git, use git diff commit1 commit2 to see the changes between two commits. You can also use git log -p commit1..commit2 to view the patch details between commits.
📐

Syntax

The basic syntax to compare commits in Git is:

  • git diff <commit1> <commit2>: Shows the differences between two commits.
  • git log -p <commit1>..<commit2>: Shows commit logs with patch details between two commits.
  • git diff <commit>: Compares a commit with the current working directory.
bash
git diff <commit1> <commit2>
git log -p <commit1>..<commit2>
git diff <commit>
💻

Example

This example shows how to compare two commits using git diff and git log -p. It demonstrates the differences in file changes and commit details.

bash
git diff 1a2b3c4 5d6e7f8

git log -p 1a2b3c4..5d6e7f8
Output
diff --git a/file.txt b/file.txt index e69de29..d95f3ad 100644 --- a/file.txt +++ b/file.txt @@ -0,0 +1,2 @@ +Hello World +This is a change commit 5d6e7f8 Author: User <user@example.com> Date: Thu Apr 27 12:00:00 2024 +0000 Added greeting to file.txt commit 1a2b3c4 Author: User <user@example.com> Date: Wed Apr 26 10:00:00 2024 +0000 Initial commit
⚠️

Common Pitfalls

Common mistakes when comparing commits include:

  • Using incorrect commit hashes or partial hashes that do not uniquely identify commits.
  • Confusing the order of commits in git diff which affects the direction of changes shown.
  • Not specifying the range correctly in git log -p, which can lead to no output or unexpected results.

Always verify commit hashes with git log --oneline before comparing.

bash
git diff 5d6e7f8 1a2b3c4  # Wrong order, shows reverse changes

# Correct order:
git diff 1a2b3c4 5d6e7f8
📊

Quick Reference

CommandDescription
git diff Show changes between two commits
git log -p ..Show commit logs with patch between commits
git diff Show changes between a commit and working directory
git diff Compare two branches
git show Show details of a single commit

Key Takeaways

Use git diff with two commit hashes to see changes between commits.
git log -p shows commit history with detailed changes (patches).
Order of commits in git diff matters; it shows changes from first to second commit.
Verify commit hashes before comparing to avoid errors.
You can also compare branches or a commit with your working directory.