How to Compare Two Branches in Git: A Developer’s Guide

Version control systems like Git make it easy to work on multiple branches, experiment with features, and collaborate with teams. But when it’s time to merge changes or review differences, you’ll often need to compare two Git branches.

In this blog post, we’ll cover several ways to compare branches in Git — from simple command-line comparisons to more advanced diff techniques.


🧠 Why Compare Git Branches?

Comparing branches helps you:

  • Identify code changes between feature and main branches.
  • Review pull requests before merging.
  • Ensure consistency before deployments.
  • Avoid merge conflicts by proactively reviewing differences.

🛠️ Basic Syntax for Comparing Branches

In Git, you can compare two branches using the following format:

git diff branch1..branch2

This shows what’s in branch2 that is not in branch1.


✅ Use Cases and Examples

1. Compare Current Branch with Another

git diff main

This compares your current working branch with main and shows changes in your current branch.

2. Compare Two Specific Branches

git diff feature-branch..main

This shows the differences from feature-branch to main — what has changed in main that isn’t in feature-branch.

Reverse the order to see the opposite:

git diff main..feature-branch

📝 Tip: Use --name-only to list only the file names that differ:

git diff main..feature-branch --name-only

📋 Compare Commit History Between Branches

If you want to compare the commit history rather than file content, use:

git log branch1..branch2

Example:

git log main..feature-branch

This shows commits that are in feature-branch but not in main.

To see a summarized version:

git log --oneline main..feature-branch

🧪 Use Git Merge Base for Accurate Comparison

To see what changed from the common ancestor:

git diff $(git merge-base main feature-branch)..feature-branch

This shows all changes in feature-branch since it diverged from main.


🖥️ Visual Comparison Tools

If you prefer graphical comparisons, you can use:

  • GitHub UI: Navigate to the repository → Pull requests → “Compare & pull request”.
  • GitKraken, Sourcetree, or VS Code Git extension: These tools provide visual diffs and easier branch comparisons.

⚠️ Common Pitfalls

  • Always check your comparison direction. branch1..branch2 shows changes in branch2 not in branch1.
  • git diff only shows unmerged differences — it doesn’t include commits already merged.
  • Don’t confuse git diff (content diff) with git log (history diff).

🏁 Conclusion

Whether you’re preparing a pull request, reviewing code, or debugging issues, knowing how to compare branches in Git is an essential skill for modern developers. With commands like git diff, git log, and visual tools, you can easily keep your codebase clean, consistent, and conflict-free.

Sharing Is Caring:

Leave a Comment