git - 我怎样才能切换到git中的另一个分支?

标签 git version-control git-checkout

哪一行是正确的?

git checkout 'another_branch'

git checkout origin 'another_branch'

git checkout origin/'another_branch'

它们之间有什么区别?

最佳答案

如果 another_branch 已经在本地存在,而你不在这个分支上,那么 git checkout another_branch 切换到这个分支。

如果 another_branch 不存在但 origin/another_branch 存在,则 git checkout another_branch 等同于 git checkout -b another_branch起源/另一个分支; git branch -u origin/another_branch.即从origin/another_branch创建another_branch,并将origin/another_branch设置为another_branch的上游。

如果两者都不存在,git checkout another_branch 返回错误。

git checkout origin another_branch 在大多数情况下返回错误。如果 origin 是一个修订版并且 another_branch 是一个文件,那么它会 check out 该修订版的文件,但这很可能不是您所期望的。 origin主要用于git fetchgit pullgit push作为remote,url的别名到远程仓库。

git checkout origin/another_branch 如果 origin/another_branch 存在则成功。它导致处于分离的 HEAD 状态,而不是在任何分支上。如果您进行新的提交,则无法从任何现有分支访问新提交,并且不会更新任何分支。

更新:

随着2.23.0的发布,我们也可以使用git switch来创建和切换分支了。

如果 foo 存在,尝试切换到 foo:

git switch foo

如果 foo 不存在而 origin/foo 存在,尝试从 origin/foo 创建 foo然后切换到 foo:

git switch -c foo origin/foo
# or simply
git switch foo

更一般地说,如果 foo 不存在,尝试从已知的 ref 或提交创建 foo,然后切换到 foo:

git switch -c foo <ref>
git switch -c foo <commit>

如果我们同时在Gitlab和Github维护一个仓库,本地仓库可能有两个远程,比如Gitlab的origin和Github的github。在这种情况下,存储库有 origin/foogithub/foogit switch foo 会报错 fatal: invalid reference: foo,因为它不知道来自哪个 ref,origin/foogithub/foo,创建 foo。我们需要根据需要用git switch -c foo origin/foo或者git switch -c foo github/foo来指定。如果我们想从两个远程分支创建分支,最好为新分支使用可区分的名称:

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

如果 foo 存在,尝试从(或将 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>

如果你只想创建一个分支而不想切换到它,请改用 git branch。尝试从已知的引用或提交创建一个分支:

git branch foo <ref>
git branch foo <commit>

关于git - 我怎样才能切换到git中的另一个分支?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47630950/

相关文章:

git - 如何更改 git repo 的所有者?

git - 我可以在 git 中强制执行仅 merge 分支吗?

visual-studio - 带有 Visual Studio 插件的源代码控制系统列表

git - 声音、视频和其他二进制文件的版本控制

GIT checkout 除了一个文件夹

git - 我们怎么理解git checkout [点]

git - 如何用实验分支替换master分支

git - 2017 年在 OS X 上从源代码构建 Apache Hadoop

svn - svn 切换后发生了什么以及如何提交本地更改?

git - 如何在 git checkout 中使用八进制字符?