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

标签 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

它实际上工作正常,但对我来说似乎不合适。 还有其他方法吗?

最佳答案

你可以试试这个来找到跟踪分支:

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 中:

Default values for <repository> and <branch> are read from the "remote" and "merge" configuration for the current branch as set by git-branch[1] --track.

关于git - 如何检查 git branch 是否有跟踪分支?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26337477/

相关文章:

git - gitflow 修补程序应该如何工作?

git - Phabricator:如何使 arc diff 忽略未跟踪的文件以及如何编辑审阅者

git - 樱桃选择问题 : changes from previous commits are also applied

bash - 为什么我会收到 'unary operator expected' 错误?

git - 使用 go 语言与 gitolite

git - 如何将 HEAD 移回以前的位置? (分离头)和撤消提交

linux - 用户登录后未执行 Bash

bash - 使用重定向创建输出日志

bash - 如何将 config ini 文件转换为 bash 中的系统环境?

arrays - Bash 数组键与现有变量冲突