How to get git parent branch name from current branch?

32,271

Solution 1

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.

Solution 2

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^

Solution 3

This one (from https://hankchizljaw.com/notes/24/) works for me:

git show-branch -a | grep '\*' | grep -v `git rev-parse --abbrev-ref HEAD` | head -n1 | sed 's/.*\[\(.*\)\].*/\1/' | sed 's/[\^~].*//'
Share:
32,271
Md. Naushad Alam
Author by

Md. Naushad Alam

Updated on February 11, 2020

Comments

  • Md. Naushad Alam
    Md. Naushad Alam about 4 years

    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.

    • Md. Khairul Hasan
      Md. Khairul Hasan almost 8 years
      not sure the questions are same but you can get answers here stackoverflow.com/questions/3161204/…
    • DAXaholic
      DAXaholic almost 8 years
      @Md.KhairulHasan The question is actually the same as you linked directly to this question again :)