Developers create and work on various branches for their projects. Sometimes, they want to find the specific two branches’ most recent common ancestor. It is the most recent commit that is shared by both branches. At this point, the two branches diverged and began to develop their unique changes. Moreover, different Git commands are available to get it.
This write-up will explain the procedure to find the two branches’ most common recent ancestor.
How to Find the Most Recent Common/Shared Ancestor of Two Branches?
First, redirect to the desired local repository to find the most common ancestor of the two branches. Then, select two branches and view their commit history. Next, execute the “git merge-base <branch1> branch2>” command. This command will find the most recent ancestor of two branches by finding the commit where they first diverged.
Step 1: Move to Local Repository
First, redirect to the particular local repository by executing the below-listed command:
Step 2: Check the Git Log of the “master” Branch
Then, run the “git log” command to view the commit history of the current branch:
Step 3: Switch to Another Branch
Next, select another desired branch and navigate to it. For instance, we have selected the “feature” branch:
Step 4: View Commit History of “feature” Branch
Now, view the list of commits in the current branch using the below-provided command:
Step 5: Perform merge-base Operation
To find the most recent common ancestor of two branches, type out the “git merge-base” command and specify two desired branches. For instance, we want to find the most recent common ancestor of the “master” and “feature” branches:
The below-provided displays the commit SHA hash for the recent common ancestor:
Step 6: Ensure Common Ancestor
Lastly, view the commit history of both branches in the form of a graph to verify the most recent common ancestor:
In the given-below output, a visual log can be seen that shows the most recent common ancestor of the “master” and “feature” branches:
We have explained the easiest method of getting the most recent common/shared ancestor of two Git branches.
Conclusion
To find the most recent shared ancestor of the two Git branches, first, navigate to the local repository. Select desired branches and execute the “git merge-base <branch1> branch2>” command. This command will return the SHA-hash of the two branches’ most recent common ancestor. This article has demonstrated the procedure to get the most recent common/shared ancestor of two Git branches.