git command to emit name of remote tracking branch

2019-02-05 20:23发布

问题:

I'd like a command that emits the name of the tracked branch for the branch I'm on. Something like:

$ git checkout --track -b topic origin/master
Branch topic set up to track remote branch master from origin.
Switched to a new branch 'topic'
$ git unknown-command
origin/master

Is there such a command?

回答1:

Will emit the remote being tracked:

git config branch.<branchname>.remote

Will emit the ref being tracked on that remote:

git config branch.<branchname>.merge

I don't believe that there is a combined command that will emit both together (at least within normal Git; you could always make your own).


For example, for a local master branch:

$ git config branch.master.remote
origin
$ git config branch.master.merge
refs/heads/master


回答2:

As per Mark Longair's request, my previous comment is now reproduced as an answer.

With recent versions of git, you can emit the name of the remote-tracking branch for your current branch with git rev-parse --symbolic-full-name @{u}. It emits something like refs/remotes/origin/master.

If you go one step further and use the --abbrev-ref flag, as in git rev-parse --symbolic-full-name --abbrev-ref @{u}, it will strip off the refs/remotes/ bit and leave you with just the short branch name, such as origin/master.



回答3:

git config --global alias.show-upstream '!sh -c '\''

    test -n "$1" || set -- HEAD
    set -- "$(git rev-parse --symbolic-full-name "$1")"
    git for-each-ref --format="%(upstream:short)" "$1"


'\'' -'

git show-upstream
git show-upstream HEAD
git show-upstream some/local/branch


回答4:

As of git 1.8.3 you can now do this:

git branch -vv 

Very convenient as it shows the tracking branch for all local branches at once, but it is not suitable for scripting.



标签: git branch