我在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 checkout -b my-branch
git commit -a -m "my commit"
git push

由于我没有找到更好的解决方案,我只是在~/.bashrc上创建了一个bash别名:

alias push="git push -u origin HEAD"

现在,只需执行push命令即可完成此任务(您也可以在~/.gitconfig上使用其他名称添加此别名,例如pushup)

其他回答

我们使用phabricator,而不是使用git。我必须创建在Linux/mac上运行的bash别名

vim ~/.bash_aliases

new_branch() {
    git checkout -b "$1"
    git branch --set-upstream-to=origin/master "$1"
}

save

source ~/.bash_aliases
new_branch test #instead of git checkout -b test
git pull

您可以使用:

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

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

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

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

这里有很多很好的答案,然而,所有这些都要求您在运行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
}