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

这将推断出原点my_branch部分,因此您可以执行以下操作:

git push -u

这将创建同名的远程分支并跟踪它。

其他回答

如果以下操作不起作用:

git config --global push.default current

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

git config --local push.default current
git branch --set-upstream-to=origin/master<branch_name>

您可以使用:

git config --global branch.autosetupmerge always

每次创建或签出新分支时,它将链接上游分支。

看见https://felipec.wordpress.com/2013/09/01/advanced-git-concepts-the-upstream-tracking-branch/

这也适用于branch.autosetuprebase,如果您遵循更注重rebase的工作流,但除非您知道自己在做什么,否则不要使用它,因为它将默认您的pull行为为rebase,这可能会导致奇怪的结果。

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

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

噢,我的zsh的git插件已经将其别名为gpsup。这将推送并设置分支的上游。一气呵成!

我个人喜欢标准化和一致的解决方案。建议其他人使用相同的别名。:)