By given name of a Git remote-tracking branch how to find which local branch tracks it?

Viewed 124

By a given name of a Git remote-tracking branch, for example, upstream/develop how to find which local branch tracks it if any?

If possible I'm looking for a solution that not relies on shell scripting and also works on Windows.

3 Answers

An alternative is to use a conditional format with for-each-ref

git for-each-ref --format="%(if:equals=upstream/develop)%(upstream:short)%(then)%(refname:short)%(end)" refs/heads | sort -u

which could be more conveniently put into an alias like

git config --global alias.who-tracks '!f() { git for-each-ref --format="%(if:equals=upstream/$1)%(upstream:short)%(then)%(refname:short)%(end)" refs/heads | sort -u; }; f'

# then when you need it :
git who-tracks develop
git who-tracks another/branch

In this alias, I assumed a unique remote, but of course if you want to be able to use it on different remotes, tweak a little bit to include the remote name in the parameter :

git config --global alias.who-tracks '!f() { git for-each-ref --format="%(if:equals=$1)%(upstream:short)%(then)%(refname:short)%(end)" refs/heads | sort -u; }; f'

# then when you need it :
git who-tracks upstream/develop
git who-tracks origin/another/branch

Another alternative is to filter the very verbose output of the simple git branch with grep

git branch -vv | grep upstream/develop

Based on this answer (branch enumeration) and this answer (retrieving upstream branch), you can iterate through local branches and check if any of them has the desired tracking remote branch:

git for-each-ref --shell \
  --format='test %(upstream:short) = "upstream/develop" && echo %(refname:short)' \
  refs/heads/ | sh
Related