我在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 branch --set-upstream-to=origin/master<branch_name>

其他回答

你可以简单地

git checkout -b my-branch origin/whatever

首先。如果您将branch.atosetupmerge或branch.atostubrebase(我最喜欢的)设置为总是(默认值为true),我的分支将自动跟踪origin/whatever。

请参阅git-help-config。

您可以使用:

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,这可能会导致奇怪的结果。

您可以设置一个非常好的别名来处理这个问题,而无需过于冗长的语法。

我在~/.gitconfig中有以下别名:

po = "!git push -u origin \"$(git rev-parse --abbrev-ref HEAD)\""

对新分支进行提交后,只需键入以下命令即可推送新分支:

git po

我个人在bash中使用以下别名

在~/.gitconfig文件中

[alias]
    pushup = "!git push --set-upstream origin $(git symbolic-ref --short HEAD)"

和~/.bashrc或~/.zshrc文件中

alias gpo="git pushup"
alias gpof="gpo -f"
alias gf="git fetch"
alias gp="git pull"

值得一提的是,如果您试图跟踪远程上已经存在的分支(例如,origin/somebranch),但尚未在本地签出,则可以执行以下操作:

$ git checkout --track origin/somebranch

注意:“-t”是“--track”选项的缩写版本。

这立刻建立了相同的关联。