Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get git parent branch name from current branch?

Currently I am in a feature branch, but I don't know whether it was created from my develop or release branch.

Can anyone please tell me how I can get the parent branch name from the current git branch.

like image 375
Md. Naushad Alam Avatar asked Jul 21 '16 05:07

Md. Naushad Alam


2 Answers

Given that Git uses a directed acyclic graph and usually a repo only has one root, all your branches point back to one initial commit. So what you actually want is the branch that shares the largest part of its history with your branch.

You cannot just look for a branch whose HEAD is contained in your current branch’s history, as this branches HEAD will most likely have moved since then.

So I recommend you use git merge-base, which finds the newest common ancestor (aka fork point) of two branches or commits:

$ git merge-base feature develop
12345abc
$ git merge-base feature release
98765fed

This will output the two commits that appear in the history of both branches, respectively. One of the two will be contained in both branches, so you can feed them to merge-base again to get the commit you want (or rather, the one you don’t want):

git merge-base 12345abc 98765fed
98765fed

So in our example, feature was derived from develop, as the two share a commit that release does not have.

Note that this will only work if you don’t do criss-cross-merges between feature and develop.

like image 102
Andreas Wolf Avatar answered Oct 10 '22 03:10

Andreas Wolf


So far this worked for me. You can use this as terminal alias in Mac or any type of shortcut on Windows.

git log --pretty=format:'%D' HEAD^ | grep 'origin/' | head -n1 | sed 's@origin/@@' | sed 's@,.*@@'

As explained in many places, it is not a direct parent, it gives you nearest branch which from current branch is created created or shares same HEAD^

like image 23
Narasimha Avatar answered Oct 10 '22 04:10

Narasimha