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

3
我正在为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个回答

6
你可以尝试以下方法来查找跟踪分支:
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"

有关跟踪分支的信息存储在特定于仓库的.git/config中,根据git pull手册

<repository>和<branch>的默认值从当前分支由git-branch[1] --track设置的"remote"和"merge"配置中读取。


是的,这似乎是找到它的好方法。我很好奇为什么rev-parse会抛出错误。 - dentuzhik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接