git中切换分支的方式及区别

5,385 阅读2分钟

git checkout

git checkout another_branch

各种情况下的表现:

  • 本地存在分支

切换分支

  • 本地不存在分支,但是远程仓库有

相当于

git checkout -b another_branch origin/another_branch

git branch -u origin/another_branch

从远端拉取最新分支到本地并切换到这个分支。

  • 本地、远端仓库均没有

报错。

git checkout origin/another_branch

各种情况下的表现:

  • 本地没有分支但是远端仓库有

会指向一个游离的 HEAD ,并不指向任何一个分支,在此基础上提交的 commit 在任何 branch 下都不会被访问到。

个人理解相当于把远端分支上的 commit 全都拉下来,HEAD 指向最新 commit ,但是并没有一个分支来保存这些 commit ,所以造成了游离状态。

  • 其他情况会报错。

git checkout origin master

此条语句在大多数情况下会报错。如果 origin 是一个修订版本,而 another_branch 是一个文件,则它将签出该修订版本的文件,但很可能不是我们所期望的。 origin 主要用于 git fetchgit pullgit push 中,作为指向远程存储库的URL的别名。

git switch

  • 本地存在分支
git switch foo
  • 本地不存在分支但是远端仓库存在
git switch -c foo origin/foo
# or simply
git switch foo
  • 在通常情况下,如果 foo 分支不存在,尝试从一个现有的分支/commit上新建这个分支并且切换可以这样:
git switch -c foo <ref>
git switch -c foo <commit>

如果我们把一个repo同时存放在多个远端库中,本地的远端库别名会有多个(例如同时存放在 GitHub 和 GitLab 上)。在这种情况下会在不同远端库上都存在相同分支,例如github_origin/foogitlab_origin/foo。 在这种情况下,执行命令

git switch foo 

会报错,因为 git 不知道我们要从哪个远端库中拉取分支。我们需要指明从哪个远端库中拉取分支,我们需要通过

git switch -c foo origin/foo
git switch -c foo github/foo

来指明远端库。当然,如果从两个 remote repository 的相同分支上都需要拉取代码,那么最好标注一下是哪个远端库的分支。例如:

git switch -c gitlab_foo origin/foo
git switch -c github_foo github/foo
  • 如果 foo 存在,从已知的 分支 或 commit 重新创建/强制创建 foo(或将foo重置),然后切换到foo:
git switch -C foo <ref>
git switch -C foo <commit>

相当于

git switch foo
git reset [<ref>|<commit>] --hard
  • 切换到已知引用或提交的游离 HEAD
git switch -d <ref>
git switch -d <commit>
  • 如果仅仅想要创建一个分支但是并不想切换到这个分支上,请用 branch ; 在已经存在的分支的基础上建立一个新的分支:
git branch foo <ref>
git branch foo <commit>