How do I get the name of the remote git
branch from which the local git
current commit was branched-off?
I assume this is a 4 step process, and that the first three steps might be as follows:
git rev-parse --abbrev-ref HEAD
git rev-parse HEAD # full hash
git rev-parse --abbrev-ref @{upstream}
What specific code is required to do this? After reading @ChrisJohnsen's answer to this other posting, I imagine that the solution involves looking for the most recent commit that was derived from another branch in the remote repository. However, the code in the answers to the linked posting all seem to be designed for local repositories. This current question is different because I am asking how to find the remote repository parent branch from a local repository child branch.
I am adding the bash
tag because these commands are running on CentOS servers that can use bash
scripting.
To get the remote parent branch by view all the branch structure, you can print the commit history as graph by any of below commands:
gitk --all
git log --oneline --decorate --graph --all
To get the remote parent branch only for a local branch by script, you can create local temp branches based on the remote branches. Then you can find the parent branch of the local branch from the temp branches. After finding the temp branch is the parent branch of the local branch, you can get the remote branch correspondingly. Finally, delete all the temp branches. Detail steps as below:
List all the remote branches by git branch -r
(assume the remote branches are origin/master
, origin/dev
and origin/feature
).
Get the tracking/remote branch from the local branch
The way to get the remote branch of the given local branch as you use the commmand git rev-parse --abbrev-ref @{upstream}
(assume it’s origin/master
branch which you want to find it’s parent branch).
Create local temp branches from remote branches separately
git branch -b origin-master origin/master #Create a local branch origin-master from origin/master
git branch -b origin-dev origin/dev
git branach -b origin-feature origin/feature
Find the parent branch from the temp branches
Now you just need to find origin-master
branch’s parent branch from all the temp branches (origin-master
, origin-dev
and origin-feature
). It converts to the same situation as the post (Find the parent branch of a Git branch) shows. And you can use the same way to achieve.
Convert the parent branch to the corresponding remote branch
Such as you find the parent branch of origin-master
branch is origin-dev
, then replace -
to /
to get the remote parent branch name origin/dev
.
Delete all the temp branches
git branch -D origin-master
git branch -D origin-dev
git branch -D origin-feature
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With