git - 为什么我需要一直执行 `--set-upstream`?

标签 git git-branch

我在 Git 中创建了一个新分支:

git branch my_branch

推送它:

git push origin my_branch

现在假设有人在服务器上做了一些更改,我想从 origin/my_branch 中提取。我这样做:

git pull

但是我得到:

You asked me to pull without telling me which branch you
want to merge with, and 'branch.my_branch.merge' in
your configuration file does not tell me, either. Please
specify which branch you want to use on the command line and
try again (e.g. 'git pull <repository> <refspec>').
See git-pull(1) for details.

If you often merge with the same branch, you may want to
use something like the following in your configuration file:

    [branch "my_branch"]
    remote = <nickname>
    merge = <remote-ref>

    [remote "<nickname>"]
    url = <url>
    fetch = <refspec>

See git-config(1) for details.

我了解到我可以使用它:

git branch --set-upstream my_branch origin/my_branch

但为什么我需要为我创建的每个分支都执行此操作?如果我将 my_branch push origin/my_branch,那么我想将 origin/my_branch pull 入 my_branch 不是很明显吗?我怎样才能使它成为默认行为?

最佳答案

一个不依赖于记住 git branch --set-upstream 1 语法的快捷方式是:

git push -u origin my_branch

... 第一次推送该分支。或者,从同名分支推送到当前分支(方便使用别名):

git push -u origin HEAD

你只需要使用 -u 一次,它会在你的分支和 origin 的分支之间建立关联,就像 git branch --set-upstream 是。

就我个人而言,我认为必须明确地在您的分支和远程分支之间建立关联是一件好事。可惜规则是different for git push and git pull .


1 这听起来可能很傻,但我经常忘记指定当前分支,假设这是默认的 - 但事实并非如此,而且结果非常困惑。

2012-10-11 更新:显然我不是唯一发现容易出错的人!感谢VonC指出 git 1.8.0 引入了更明显的 git branch --set-upstream-to,如果你在分支 my_branch 上,可以按如下方式使用>:

git branch --set-upstream-to origin/my_branch

...或使用短选项:

git branch -u origin/my_branch

此更改及其推理在 the release notes for git 1.8.0, release candidate 1 中进行了描述:

It was tempting to say git branch --set-upstream origin/master, but that tells Git to arrange the local branch origin/master to integrate with the currently checked out branch, which is highly unlikely to be what the user meant. The option is deprecated; use the new --set-upstream-to (with a short-and-sweet -u) option instead.

Git v2.37.1 及以上

如果您使用的是上述版本或更高版本,您可以使用这个新的配置条目来自动设置远程跟踪:

git config --global push.autoSetupRemote true

关于git - 为什么我需要一直执行 `--set-upstream`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6089294/

相关文章:

git - 如何在并发环境中实际使用 Git

django - Git 神秘地删除东西(编辑 : actually django-storages)

git - 清理远程 Git 分支

Git - 在 github 上使用端口 9418 进行远程操作

linux - 在远程 ssh 虚拟机上运行命令并在本地存储响应

git - 我可以只从另一个 git 存储库中提取某些文件吗?

git - 如果 git pull 请求仍待处理,我如何继续跨分支工作?

git - 为什么 git branch 不显示任何东西?

git - 远程 : Unauthorized fatal: Authentication failed Bitbucket

git:在不分离头部的情况下切换分支