How to Identify the Recent Common Ancestor for Two Branches in Git
This article illustrates how we can find the recent common ancestor commit in Git. This comes in handy when you create or merge a branch onto another.
Without further ado, let’s jump into today’s agenda.
Identify the Recent Common Ancestor for Two Branches in Git
What is a common ancestor for two branches in Git?
Take a look at the image below.
In the image above, we have the main
branch where we have created a feature
branch and a new feature
branch off the feature
branch. Let’s do away with the main
branch and focus on the feature
and new-feature
branches.
We can see that we created the new-feature
branch after the bd9172c
commit. As you might have guessed, the bd9172c
commit is our recent common ancestor for the feature
and main
branches.
So, how do we find the recent common ancestor for the two branches?
All you need is the git merge-base
command. From Git’s documentation, the git merge-base
command helps us find the best common ancestor for a git merge
.
However, we can feed in two branches as an argument to display the most recent common ancestor for the supplied branches.
Syntax:
$ git merge-base <Branch 1> <Branch 2>
Let’s look at an example.
The example below shows our local repository’s master
and feature
branches. To find the common ancestor between the two, we will run the git merge-base
command, as shown below.
$ git merge-base master feature
This command should display the commit hash for the common ancestor.
Output:
We can use the command below for a visual log.
$ git log --graph --oneline --all --decorate
You should get something like this:
We can see that our feature
branch forked from the master
at the 2dbe38d
commit, which is the same commit hash we got from running the git merge-base
command earlier.
You can find the most recent common ancestor commit for two branches in Git using the git merge-base
command while feeding in the branches at hand. Note that this command only gets the most recent common ancestor.
John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.
LinkedIn