获取 Git 分支的跟踪信息

Getting tracking information for a Git branch

如何获取有关特定本地 Git 分支的跟踪信息(即远程和分支名称),最好是在一个命令中?似乎有很多方法可以做到这一点,例如

git rev-parse --abbrev-ref --symbolic-full-name branch_name@{upstream}

然而,它 returns 上游的形式是 'origin/branch_name',这使得很难找出单独的部分(例如,当远程或分支名称包含 '/' 时)。是否有更可靠的解决方案,最好使用单个 Git 命令?

我会使用内置的 -v(详细)甚至 -vv(非常详细)标志从 git branch 输出中获取它。您也可以只搜索分支名称以专注于您想要的内容:

git branch -vv | grep <branchName>

根据您具体想要得到什么,也许还可以考虑使用管道工具:

git for-each-ref --format="%(upstream:short)" refs/heads/<yourBranch>

并为方便起见将其设为别名

git config --global alias.get-rem '!f() { git for-each-ref --format="%(upstream:short)" refs/heads/; }; f'

# then just
git get-rem branch_name

编辑: 对于非常短的部分(即 "branch" 而不是 "refs/remotes/origin/branch" 甚至 "origin/branch"),您可以使用 %(upstream:lstrip:-1) 而不是 %(upstream:short)

@RomainValeri in the 建议使用此命令显示跟踪信息。

git for-each-ref --format="%(upstream:short)" refs/heads/<yourBranch>

但是,如果你想去掉斜杠,那么你可以这样做

git for-each-ref --format="%(upstream:remotename) %(upstream:lstrip=-1)"  \ 
# Insert your separator here                     ^
refs/heads/<yourBranch>

来自 git-docs,

upstream

The name of a local ref which can be considered “upstream” from the displayed ref. Respects :short, :lstrip and :rstrip in the same way as refname above ...

For any remote-tracking branch %(upstream), %(upstream:remotename) and %(upstream:remoteref) refer to the name of the remote and the name of the tracked remote ref, respectively. In other words, the remote-tracking branch can be updated explicitly and individually by using the refspec %(upstream:remoteref):%(upstream) to fetch from %(upstream:remotename).

有关 lstrip

的更多信息

If lstrip= < N > (rstrip= < N >) is appended, strips < N > slash-separated path components from the front (back) of the refname (e.g. %(refname:lstrip=2) turns refs/tags/foo into foo and %(refname:rstrip=2) turns refs/tags/foo into refs). If < N > is a negative number, strip as many path components as necessary from the specified end to leave -< N > path components (e.g. %(refname:lstrip=-2) turns refs/tags/foo into tags/foo and %(refname:rstrip=-1) turns refs/tags/foo into refs). When the ref does not have enough components, the result becomes an empty string if stripping with positive < N >, or it becomes the full refname if stripping with negative < N >. Neither is an error.


一些示例:

  • 格式:"%(upstream:remotename):%(upstream:lstrip=-1)"

    输出:<remote-name>:<branch-name>

  • 格式:"%(upstream:remotename) %(upstream:lstrip=-1)"

    输出:<remote-name> <branch-name>


如果分支名称包含斜杠,则 lstrip 将不起作用。而是可以使用 remoteref

git for-each-ref --format="%(upstream:remotename) %(upstream:remoteref)" refs/heads/<yourBranch>

输出格式如下:<remote-name> refs/heads/<branch-name>

要从输出中删除 refs/heads/,请将上述命令通过管道传递给此

sed 's/refs\/heads\///g'