哪一行是正确的?
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 fetch
、git pull
和git 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/foo
和 github/foo
。 git switch foo
会报错 fatal: invalid reference: foo
,因为它不知道来自哪个 ref,origin/foo
或 github/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/