git 指针
所以切换分支的本质就是移动HEAD 指针。
游离原因
一般我们会使用命令 git checkout <branch_name>
来切换分支,HEAD 就会移动到指定的分支上。
但是,如果我们使用的是git checkout <commit_id>
来切换到指定的某一次提交,HEAD 就会处于「detached」状态,也就是游离状态。
HEAD 游离状态的利弊
好处:HEAD 处于游离状态时,开发者可以很方便地在历史版本之间互相切换,比如要回到某次提交,只需要 checkout 对应的 commit id 或者 tag 名即可。
弊端:若在该基础上进行了提交,则会新开一个「匿名分支」;也就是说我们的提交是无法可见保存的,一旦切换到别的分支,原游离状态以后的提交就不可追溯了。
问题现象:
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)这种奇怪的本地版本 这样的提示.
对git checkout commit_id后出现游离态
1. git commit # 对本地修改进行提交 (提交完你的本地分支指向的是你刚commit完的状态码 类似:06763f6)可以通过git reflog查看操作记录
2. git branch temp 06763f6 #这句执行是在本地创建一个temp分支 并将你刚才commit的内容放到新分支里面存储
3. git checkout temp #切换到刚才新建的分支 (如果你已经处于temp分支 可以忽略这一步)
4. git checkout master #切换到你原来的开发的分支 (master只是一个分支 你可以切换到你的任意分支 )
5. git merge temp #将之前存储到short分支上的内容合并到你当前的分支上
6. git branch -d temp #删除short临时分支 (可以不删除)ps:有的电脑上-d参数不生效 需要-D才生效