小编典典

本地分支、本地跟踪分支、远程分支和远程跟踪分支有什么区别?

all

我刚开始使用 Git,我对不同的分支感到非常困惑。谁能帮我弄清楚以下分支类型是什么?

  • 当地分支机构
  • 本地跟踪分支
  • 远程分支
  • 远程跟踪分支

它们之间有什么区别?他们如何相互合作?

我猜一个快速的演示代码会很有帮助。


阅读 60

收藏
2022-07-13

共1个答案

小编典典

本地分支 是只有您(本地用户)可以看到的分支。它仅存在于您的本地计算机上。

git branch myNewBranch        # Create local branch named "myNewBranch"

远程分支 是远程位置的分支(在大多数情况下)origin。您可以将新创建​​的本地分支推myNewBranch送到origin.
现在其他用户可以跟踪它。

git push -u origin myNewBranch   # Pushes your newly created local branch "myNewBranch"
                                 # to the remote "origin".
                                 # So now a new branch named "myNewBranch" is
                                 # created on the remote machine named "origin"

远程跟踪分支
是远程分支的本地副本。当myNewBranch被推送到使用上面的命令时,会在你的机器上创建origin一个名为的远程跟踪分支。origin/myNewBranch这个远程跟踪分支跟踪远程分支myNewBranchorigin您可以使用或更新
远程跟踪分支 以与 远程分支 同步。git fetch``git pull

git pull origin myNewBranch      # Pulls new commits from branch "myNewBranch" 
                                 # on remote "origin" into remote tracking
                                 # branch on your machine "origin/myNewBranch".
                                 # Here "origin/myNewBranch" is your copy of
                                 # "myNewBranch" on "origin"

本地跟踪分支 是跟踪另一个分支的本地 分支
。这样您就可以向/从另一个分支推送/拉取提交。大多数情况下,本地跟踪分支跟踪远程跟踪分支。当您将本地分支推送到origin使用git push带有-u选项的命令时(如上所示),您设置本地分支myNewBranch以跟踪远程跟踪分支origin/myNewBranch。这是需要使用的git push,并且git pull没有指定要推入或拉出的上游。

git checkout myNewBranch      # Switch to myNewBranch
git pull                      # Updates remote tracking branch "origin/myNewBranch"
                              # to be in sync with the remote branch "myNewBranch"
                              # on "origin".
                              # Pulls these new commits from "origin/myNewBranch"
                              # to local branch "myNewBranch which you just switched to.
2022-07-13