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

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

git push -u

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

更新: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"

99%的时间我想将上游设置为同名分支,所以我使用这个(在*nix或GitBash中):

git branch --set-upstream-to=origin/$(git branch --show-current)

这很好,因为它是分支不可知的。请注意,子命令gitbranch--show current会打印当前的分支名称,如果已分离,则不打印。

附带说明:我的配置设置为可以使用gitpush-u,所以我很少需要这样做。但我有时还是会这样做,通常是在我决定要将本地更改重置为远程设备上的任何更改时,这时我意识到我以前在推送时没有使用-u。因此,通常,在设置上游后,我要运行的下一个命令是重置远程分支:

git reset --hard @{u}

这也恰好是分支不可知的。(也许我真的不喜欢输入我的分行名称。)

我个人在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"

显然没有支持的方法来覆盖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'