04
Comparing Changes Between Two Branches in Git
When working with Git, it's common to have multiple branches for different features, bug fixes, or releases. Some times, you might need to compare the changes between two branches to understand what modifications have been made. In this Blog, we'll walk through the steps to compare two branches in Git, with a focus on identifying changes made in one branch relative to another.
Scenario
Let's assume you have two branches, branch1
and branch2
. branch2
was created from branch1
and has some new commits. You want to see what changes have been made in branch2
since it was branched off from branch1
.
Steps to Compare Branches
1. Fetch the Latest Changes
First, ensure your local repository is up to date with the remote repository. This step ensures you have the latest commits from all branches.
git fetch
2. Check Out the Branches
While you don't need to check out the branches to compare them, it's a good practice to ensure you know which branch you are currently on. Let's check out branch2
.
git checkout branch2
3. Compare the Branches Using git diff
To see the changes in branch2
relative to branch1
, you can use the git diff
command.
git diff branch1..branch2
This command shows the differences between branch1
and branch2
, highlighting what has been added, modified, or deleted in branch2
since it diverged from branch1
.
4. Review the Differences
The output of git diff branch1..branch2
will display the line-by-line changes between the two branches. Additions are usually marked with a +
and deletions with a -
. This detailed output helps you understand exactly what has changed in branch2
.
5. View Commit Logs
In addition to the line-by-line differences, you might also want to see the specific commits that introduced the changes in branch2
. You can do this using the git log
command:
git log branch1..branch2
This command lists all the commits on branch2
that are not in branch1
, giving you a clear view of the history and context of the changes.