0

I am trying to find which local branch would have been the default when cloning a git repository.

In this particular context I am able to assume the remote is called origin. I can get the default branch for origin using git symbolic-ref refs/remotes/origin/HEAD. This returns something like refs/remotes/origin/develop.

I now need to find which local branches are set up to track origin/develop. Obviously it's almost certainly going to be develop, so I could just do some string manipulation to replace remotes/origin/ and end up with refs/heads/develop. However, I would like to avoid making that assumption.

I'm currently grepping it out of the result of git branch -vv (specifically git rev-parse --symbolic-full-name $(git branch -vv | grep "\[$(git rev-parse --abbrev-ref $(git symbolic-ref refs/remotes/origin/HEAD))\]" | awk '{print $1}')). However, this is very brittle, especially as the branch name can appear in the commit message.

I am currently using git 2.18, though could upgrade if newer verisons have a feature required to make this better.

0

2 Answers 2

2

You can also take advantage of the %(if) %(then) [%(else)] %(end) construct inside for-each-ref formats.

git for-each-ref --format="%(if:origin/<remoteBranch>)%(upstream:short)%(then)%(refname:short)%(end)" refs/heads 

(As a sidenote, in case you have many branches, avoid the blank lines noise by adding | sort -u )


Finally, this is a lot more convenient in an alias :

git config --global alias.get-branches-pointing-to '!f() { git for-each-ref --format="%(if:equals=origin/$1)%(upstream:short)%(then)%(refname:short)%(end)" refs/heads | sort -u; }; f' git get-branches-pointing-to <yourRemoteBranch> 
Sign up to request clarification or add additional context in comments.

Comments

0
git for-each-ref refs/heads --format='%(refname:short) %(upstream:short)' | while read branch upstream; do if [ "$upstream" == origin/master ]; then echo branch "$branch" tracks "$upstream" fi done 

See https://git-scm.com/docs/git-for-each-ref

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.