Git: Find the most recent common ancestor of two branches

GitGit Branch

Git Problem Overview


How to find the most recent common ancestor of two Git branches?

Git Solutions


Solution 1 - Git

You are looking for git merge-base. Usage:

$ git merge-base branch2 branch3
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

Solution 2 - Git

git diff master...feature

shows all the new commits of your current (possibly multi-commit) feature branch.

man git-diff documents that:

git diff A...B

is the same as:

git diff $(git merge-base A B) B

but the ... is easier to type and remember.

As mentioned by Dave, the special case of HEAD can be omitted. So:

git diff master...HEAD

is the same as:

git diff master...

which is enough if the current branch is feature.

Finally, remember that order matters! Doing git diff feature...master will show changes that are on master not on feature.

I wish more git commands would support that syntax, but I don't think they do. And some even have different semantics for ...: https://stackoverflow.com/questions/462974/what-are-the-differences-between-double-dot-and-triple-dot-in-git-com

Solution 3 - Git

As noted in a prior answer, although git merge-base works,

$ git merge-base myfeature develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

If myfeature is the current branch, as is common, you can use --fork-point:

$ git merge-base --fork-point develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

This argument works only in sufficiently recent versions of git. Unfortunately it doesn't always work, however, and it is not clear why. Please refer to the limitations noted toward the end of this answer.


For full commit info, consider:

$ git log -1 $(git merge-base --fork-point develop) 

Solution 4 - Git

With gitk you can view the two branches graphically:

gitk branch1 branch2

And then it's easy to find the common ancestor in the history of the two branches.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTedView Question on Stackoverflow
Solution 1 - GitCB BaileyView Answer on Stackoverflow
Solution 2 - GitCiro Santilli Путлер Капут 六四事View Answer on Stackoverflow
Solution 3 - GitAsclepiusView Answer on Stackoverflow
Solution 4 - GitMartin GView Answer on Stackoverflow