Frequently asked questions around Git and Version Control.
How to Compare Two Branches in Git
Especially before merging or deleting a branch, you might want to compare it to another one. This gives you an overview of new changes and helps you decide if it should be integrated (or maybe deleted).
In this short article, we'll talk about the different ways to compare branches: you can compare commits, actual changes, or even a specific file on two branches.
The Git Cheat Sheet
No need to remember all those commands and parameters: get our popular "Git Cheat Sheet" - for free!
Let's say you'd like to take a look at a feature branch named "feature/login". You want to see all changes that are different from "main" - to get an idea of what would be integrated if you performed e.g. a git merge now.
git diff with Double Dot Notation
You can see this by using the git diff command as follows:
$ git diff main..feature/login
It's important to understand what exactly is being compared: using the ".." notation, Git compares the tips (= latest commits) on both branches:
Tip: you might also see notations where the two branches are separated by only a space charater (e.g. git diff main feature/login). This produces the same output as separating the branches with the two dot characters.
git diff with Triple Dot Notation
If you add a third dot to this notation, the comparison will be quite different: instead of comparing the tips of both branches, something else happens. Git now compares the tip of our feature branch with the common ancestor commit of both branches:
In most situations when you want to compare two branches, you will want to use the double dot notation, though!
Comparing Branches in Tower
In case you are using the Tower Git GUI, comparing branches is very easy. You can simply select the branches in the sidebar, right-click, and select the "Compare..." option from the contextual menu. Tower will then start a comparison and show the differing changes in your favorite diff tool.
Comparing Commits Between Two Branches
Instead of the actual, detailed changes, you can also have Git show you the commits that are different. The solution is very similar, although we have to use the git log command in this case:
$ git log main..feature/login
git log is a command with dozens of interesting options. Feel free to tinker around a bit, for example by using the --oneline option to make the output a bit more concise:
$ git log --oneline main..feature/login
Comparing A Specific File Between Branches
Sometimes, you might want to compare how exactly a certain file is different in two branches. Simply add the file's path to our git diff command from above:
$ git diff main..feature/login index.html
This will help you find out how the file "index.html" was changed in the feature/login branch - compared to what it looks like in the main branch.