git游離狀態產生的原因是:使用git命令checkout版本時,不小心checkout到了遠程分支,但此分支本地並沒有,因此此時會處於 'detached HEAD' 狀態,
即本地HEAD找不到本地分支會指向遠程分支的最后一次提交.
問題現象:
一.會提示
You are in 'detached HEAD' state. You can look around, make experimental changes and commit them,
and you can discard any commits you make in this state without impacting any branches by switching back to a branch.
If you want to create a new branch to retain commits you create,
you may do so (now or later) by using -c with the switch command.
Example: git switch -c Or undo this operation with: git switch- Turn off this advice by setting config variable advice.detachedHead
to false HEAD is now at da589bf6
二.此時運行git branch -a發現有(HEAD detached at xxx)這種奇怪的本地版本 這樣的提示.
此時不要慌,百度了很多,都是這種解決方法 https://www.cnblogs.com/kibana/p/8917501.html 但明顯是天下文章一大抄,這種其實沒有說全,明顯的硬傷是在第二步時根本無法切到主分支,
因為此問題的核心是本地沒有遠程的主分支.
此時建議:
1.git fetch 獲取所有分支,先獲取所有最新遠程分支
2.git branch -a 所有分支,查看所有分支
3.git checkout -b 4.0 origin/mrh/4.0.0 拉取遠程到本地
4.git branch tmp da589bf6 創建一個臨時分支合並上面最后一次提交id
5.git checkout 4.0 再切到本地4.0,准備合並臨時分支
6.git merge tmp 合並臨時分支
此時會提示 Your branch is ahead of 'origin/mrh/4.0.0' by 2 commits. (use "git push" to publish your local commits) 提示比遠程分支比2個版本,
說明即將成功了,合並了最新的改動(這時因為我本地同時有最新的改動,瞎操作導致的,一般游離應該不會有) 重新push到origin/mrh/4.0.0 遠程分支后再次使用git branch -a查看,
發現沒有了 (HEAD detached at xxx) 這種版本,說明成功解決了.
7.此時可以刪除tmp分支了,git branch -D tmp 刪除分支.