我在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推到origin/my_branch,那么我会想将origin/mi_branch拉到my_brance,这不是很明显吗?如何将此设置为默认行为?


当前回答

如果以下操作不起作用:

git config --global push.default current

您还应该更新项目的本地配置,因为您的项目可能具有本地git配置:

git config --local push.default current

其他回答

在git2.37.0或更高版本中,您可以告诉git自动设置远程。这是用完成的

git config --global --add --bool push.autoSetupRemote true

然后你可以只写gitpush,它将推送到默认的远程。

您可以通过两种方式更简单地设置上游。创建分支时首先:

git branch -u origin/my-branch

或者在创建分支后,可以使用此命令。

git push -u origin my-branch

您还可以在一个命令中分支、检出和设置上游:

git checkout -b my-branch -t origin/my-branch

我个人倾向于使用两步命令:

git checkout -b my-branch
git push -u origin my-branch

更新:push.autoSetupRemote现在终于以更简单的方式解决了这个问题!有关更多信息,请参阅此处的另一个答案。

原答覆:

我使用这个Git别名,而不是每次从Git复制/粘贴建议:https://gist.github.com/ekilah/88a880c84a50b73bd306

复制的源代码如下(将其添加到~/.gitconfig文件中):

[alias]
  pushup = "!gitbranchname() { git symbolic-ref --short HEAD; }; gitpushupstream() { git push --set-upstream origin `gitbranchname`; }; gitpushupstream"

99%的时间我想将上游设置为同名分支,所以我使用这个(在*nix或GitBash中):

git branch --set-upstream-to=origin/$(git branch --show-current)

这很好,因为它是分支不可知的。请注意,子命令gitbranch--show current会打印当前的分支名称,如果已分离,则不打印。

附带说明:我的配置设置为可以使用gitpush-u,所以我很少需要这样做。但我有时还是会这样做,通常是在我决定要将本地更改重置为远程设备上的任何更改时,这时我意识到我以前在推送时没有使用-u。因此,通常,在设置上游后,我要运行的下一个命令是重置远程分支:

git reset --hard @{u}

这也恰好是分支不可知的。(也许我真的不喜欢输入我的分行名称。)

因为git能够将不同的分支推/拉到不同的“上游”存储库。您甚至可以使用单独的存储库来推送和拉取同一个分支。这可以创建一个分布式、多层次的流,我可以看到这在诸如Linux内核之类的项目上非常有用。Git最初是为用于该项目而构建的。

因此,它没有假设您的分行应该跟踪哪个回购协议。

另一方面,大多数人不会以这种方式使用git,因此它可能是一个很好的默认选项。

Git通常是相当低级的,它可能会令人沮丧。然而,有GUI,如果您仍然想从shell使用它,那么编写助手脚本应该很容易。