git push -u是什么意思?

358

我有两个不同版本的git。在1.6.2版本中,git push 命令没有 -u 选项,只有在1.7.x版本中才有。

从文档中可以看到,-u 选项与变量有关。

branch.<name>.merge

git config 中,此变量如下所述:

Defines, together with branch.<name>.remote, the upstream branch 
for the given branch. It tells git fetch/git pull which branch to merge.

什么是上游分支?


1
请参见https://dev59.com/QHE85IYBdhLWcg3whD3j#2749166。 - VonC
3个回答

411
“Upstream” 指的是其他人将从中拉取代码的主要仓库,例如您的 GitHub 仓库。-u 选项会自动为您设置上游,将您的仓库链接到中央仓库。这样,在将来,Git 就“知道”您想要推送和拉取的位置,因此您可以使用 git pullgit push 而无需参数。稍微往下看,this article 解释并演示了这个概念。

20
我注意到您提供的链接中已经指出了这一点,但由于这是一个容易被忽视的问题,我认为值得指出:使用git push推送的分支,除非你将push.default设置为tracking(或在较新版本的git中设置为upstream),否则不受上游分支配置的影响。 - Mark Longair
我不明白为什么Eclipse EGit两者都提供? - HaveAGuess
27
也许是出于同样的原因,Eclipse也会带来痛苦和绝望。 - twiz
2
文章不再起作用了。 - Danilo Davanso

16

当您第一次推送新分支时,请使用:

git push -u origin <branch>

之后,您只需键入更短的命令:

git push

-u选项第一次使用时,会在本地分支上创建一个持久的上游跟踪分支。


11

这已经过时了!

Push.default is unset; its implicit value has changed in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the traditional behavior, use:

  git config --global push.default matching

To squelch this message and adopt the new behavior now, use:

  git config --global push.default simple

When push.default is set to 'matching', git will push local branches
to the remote branches that already exist with the same name.

Since Git 2.0, Git defaults to the more conservative 'simple'
behavior, which only pushes the current branch to the corresponding
remote branch that 'git pull' uses to update the current branch.

-u 选项的作用如下: 对于每个已经更新或成功推送的分支,添加上游(跟踪)引用,被 argument-less git-pull 和其他命令使用。因此,在使用 -u 选项推送本地分支后,该本地分支将自动与远程分支关联,并且您可以无需任何参数使用 git pull。


2
但是现在标志“-u”代表什么?GitHub仍建议我们在创建新存储库时使用此标志... - Jean Paul
11
-u选项的作用是:对于每个已经更新或成功推送的分支,添加上游(跟踪)引用,供不带参数的git-pull等命令使用。因此,使用-u选项将本地分支推送到远程后,该本地分支将自动链接到远程分支,您可以在不带任何参数的情况下使用git pull命令。 - Bergrebell
感谢@Melebius的提示 - 我已相应更新了答案。 - Bergrebell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接