我在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

其他回答

对于那些希望使用git pull的别名的人,我使用的是:

alias up="git branch | awk '/^\\* / { print \$2 }' | xargs -I {} git branch --set-upstream-to=origin/{} {}"

现在,只要您得到:

$ git pull
There is no tracking information for the current branch.
...

只需运行:

$ up
Branch my_branch set up to track remote branch my_branch from origin.
$ git pull

你可以走了

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

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

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

更新: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"

通过运行以下git命令之一,可以让git自动创建上游分支

git-config--global--添加push.default电流git-config--global--add push.autoSetupRemote true

git branch --set-upstream-to=origin/master<branch_name>