Compare Two Branches in Git

Compare Two Branches in Git

Before merging or deleting a branch, it's a good idea to compare it with another branch. This helps to review the changes it contains and decide whether it's ready to be merged or safe to remove. This tutorial explains how to compare two branches in Git.

1. Differences between branches

The git diff command with the .. notation compares the latest commits of the specified branches and shows the differences. Alternatively, we can use a space instead of the double dots to specify the two branches for comparison. The syntax is:

git diff branch_1..branch_2
git diff branch_1 branch_2

This shows the difference from branch_1 to branch_2, meaning it will display changes in branch_2 that are not in branch_1.

For example, to compare changes between master and my_branch, run:

git diff master..my_branch

We can also compare the current branch against master with:

git diff master..

2. Export changes to patch file

If you want to save the differences to a patch file, you can redirect the output:

git diff master..my_branch > changes.patch

This is helpful for sharing changes or applying them elsewhere using git apply.

3. Compare specific file between branches

To limit the comparison to a specific file, such as config/test.yaml, use:

git diff master..my_branch config/test.yaml

This is useful when you're only interested in changes made to a particular file.

4. List only changed files

If you're only interested in which files have changed (without showing the changes themselves), add the --name-only option:

git diff master..my_branch --name-only

This provides a clean list of modified files between the two branches.

Leave a Comment

Cancel reply

Your email address will not be published.