如何检查git branch是否有跟踪分支?

时间:2014-10-13 10:09:52

标签: git bash

我正在为bash编写一个小git帮助器,我需要知道某个名称的分支是否有跟踪分支。

更具体地说,问题是如果您在没有跟踪分支的分支上运行git pull,它将失败并显示以下内容:

There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details

git pull <remote> <branch>

If you wish to set tracking information for this branch you can do so with:

git branch --set-upstream-to=origin/<branch> foo

git pull --quiet也无法取消此消息。

我设法找到了这个有用的捷径:

git rev-parse --symbolic --abbrev-ref foo@{u}

它完全符合我的需要,如果存在跟踪分支,则输出以下内容:

origin/foo

但是如果分支机构没有跟踪分支,那么输出就是:

fatal: No upstream configured for branch 'foo'

这是相当不错的,除了它存在非零状态,并将其输出到stderr。

所以我基本上想做的是:

tracking_branch=$(git do-some-magick foo)
if [[ -n $tracking_branch ]]; then
    git pull
fi

而不是:

tracking_branch=$(git rev-parse --symbolic --abbrev-ref foo@{u} 2> /dev/null)
if [[ -n $tracking_branch ]]; then
    git pull
fi

它确实很好,但对我来说似乎并不合适。 还有其他方法吗?

1 个答案:

答案 0 :(得分:5)

您可以尝试这样找到跟踪分支:

git config --get branch.foo.merge

示例:

$ git config --get branch.master.merge
refs/heads/master

$ git config --get branch.foo.merge # <- nothing printed for non-tracked branch "foo"

根据the manual for git pull,有关跟踪分支的信息存储在特定于存储库.git/config中:

  

&lt; repository&gt;的默认值和&lt; branch&gt;从&#34;遥控器&#34;中读取和&#34;合并&#34;由git-branch [1] --track。

设置的当前分支的配置
相关问题