0
0
GitHow-ToBeginner · 3 min read

How to Compare Branches in Git: Simple Commands Explained

To compare branches in Git, use git diff branch1..branch2 to see code differences and git log branch1..branch2 to view commits unique to one branch. These commands help you understand what changes exist between branches before merging.
📐

Syntax

The basic syntax to compare branches in Git uses the git diff and git log commands with two branch names separated by two dots (..).

  • git diff branch1..branch2: Shows code differences between branch1 and branch2.
  • git log branch1..branch2: Lists commits that are in branch2 but not in branch1.
bash
git diff branch1..branch2
git log branch1..branch2
💻

Example

This example compares the main branch with a feature branch called feature1. It shows the code differences and the commits unique to feature1.

bash
git diff main..feature1
git log main..feature1 --oneline
Output
diff --git a/app.js b/app.js index 83db48f..bf12e3a 100644 --- a/app.js +++ b/app.js @@ -1,5 +1,7 @@ console.log('Hello World'); +console.log('New feature added'); 3f4e2a1 Add new feature logging
⚠️

Common Pitfalls

Common mistakes when comparing branches include:

  • Using a single dot (.) instead of two dots (..) which changes the meaning.
  • Confusing the order of branches; branch1..branch2 shows changes in branch2 not in branch1.
  • Not fetching latest changes before comparing, leading to outdated results.

Always fetch updates with git fetch before comparing.

bash
git diff main.feature1  # Wrong: single dot instead of two dots

# Correct usage:
git diff main..feature1
📊

Quick Reference

CommandPurpose
git diff branch1..branch2Show code differences between two branches
git log branch1..branch2List commits in branch2 not in branch1
git fetchUpdate remote tracking branches before comparing
git diff branch1...branch2Show changes from the common ancestor to branch2 (three dots)

Key Takeaways

Use git diff branch1..branch2 to see code differences between branches.
Use git log branch1..branch2 to view commits unique to the second branch.
Always fetch latest changes with git fetch before comparing branches.
Remember the order of branches matters in comparison commands.
Avoid using a single dot; use two dots (..) to compare branches correctly.