我在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,这不是很明显吗?如何将此设置为默认行为?


当前回答

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

$ git checkout --track origin/somebranch

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

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

其他回答

我做了一些类似于许多其他用户的事情,但我想分享它作为一种替代,因为我没有看到其他人发布这篇文章。

alias gpu='git push --set-upstream origin $(git branch --show-current)'

(噢,我的zsh已经有一个gpu别名,在.oh-my-zsh/plugins/git/git.plugin.zsh中进行了编辑)

这是我最常用的“操”。

$ git push
fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin master

$ fuck
git push --set-upstream origin master [enter/↑/↓/ctrl+c]
Counting objects: 9, done.
...

此外,在终端中键入脏话也很有趣。

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

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

更新: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 pull之前正确地执行其他操作

使用别名来完成诸如“通过创建本地正在正确跟踪的远程分支,使git push按应有的方式工作”之类的工作当然会有所帮助。然而,当你忘记使用它们,或者经历了不同的工作流程时,这些都不会对你有所帮助。

这里有一个bash函数,您可以使用它来按应该的方式进行拉取,方法是检测何时未配置远程合并目标,但远程上有一个与本地分支同名的分支,然后将该分支设置为合并目标,然后进行拉取。

git-pulldown() {
    head="$(git rev-parse --abbrev-ref HEAD)"

    if [[ $(git config "branch.$head.merge") ]]; then #there's already a merge target configured, just pull as normal from there
        git pull
    else
        if [[ $(git ls-remote --heads origin $head) ]]; then #there is an upstream branch existing with the same name as our branch
            git branch --set-upstream-to origin/$head #set merge target to upstream branch with same name
            git pull
        else #fail with explanation
            echo "Branch $head has no upstream or merge target! You will likely have to push first, or manually configure it"
            return 1
        fi
    fi
}