我在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命令的默认选项。根据对定义与shadow原始命令同名的git别名的回答,我们可以重写bash中git push的行为,始终调用git push-u。将以下内容放在~/.bash_profile文件中,它应该相当于每次推送时都在上游运行--set。

function do_git {
  cmd=$1
  shift
  myArgs=( "$@" )

  if [ "$cmd" == "push" ]; then
    myArgs=( "-u" "${myArgs[@]}" )
  fi
  myArgs=( "$cmd" "${myArgs[@]}" )

  $(which git) "${myArgs[@]}"
}
alias  git='do_git'

其他回答

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

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

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

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

git po

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

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

因为这个问题,我重新发现了合法性(仅限OS X)。现在,我在分支时只使用以下两个命令:

合法发布将指定的分支发布到远程。(别名:pub)

合法取消发布<branch>从远程删除指定的分支。(别名:unp)

SublimeGit默认情况下具有合法支持,这使得整个分支例程像按Ctrl-b一样简单。

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

对于那些希望使用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

你可以走了