赞
踩
究竟什么是分离头指针呢,它指的是HEAD不指向任何分支,而指向某次提交。我们用git checkout c2,来分离头指针 [ c2 指的是commit id 实际应用中为16进制,比如 6571e1ad805767222f3e083f389e0ebeb7769ad5,实际使用可以取前几位]
当你执行完 git checkout 6571e1a 后,会有下面的提示,提示你在分离头指针状态,在这个状态下修改提交的代码不会提交到正常的分支
- Note: switching to '6571e1a'.
-
- 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 <new-branch-name>
-
- Or undo this operation with:
-
- git switch -
-
- Turn off this advice by setting config variable advice.detachedHead to false
-
- HEAD is now at 6571e1a 初始化文件
翻译过来就是,Git提示你现在处于“分离头指针状态”,你可以查看、并且做些代码调试,还可以提交他们,在这种状态下,如果checkout到其他分支,完全可以丢弃在此基础上做的修改,而不会影响到其他分支。
如果你想保留本次的修改,你可以使用”git switch -c 新的分支名”来保留它(现在或者以后都可以)。
或者不想保存 git switch 切换到别的分支
值得注意的是:我们的提交是无法可见保存的,一旦切到别的分支,游离状态以后的提交就不可追溯了。【除非你记得自己当时的commit id,但是大多数情况记不住,所以这是危险的】
分离头指针下修改
如果在分离头指针状态下对文件做了修改,并执行了git add .和git commit进行了提交,git commit会得到下面的提示
- [detached HEAD 4f544b3] 指针分离
- 1 file changed, 1 insertion(+), 1 deletion(-)
4f544b3为在分离头指针下提交的commit id,这个commit id回到master head是看不到的,回到master 重新执行git checkout 4f544b3可找回自己的代码,执行git log时也可以看到log
- commit 4f544b3dde1992d0bcfa91d6334efff73d6b783f (HEAD)
- Author: Stronger <231@qq.com>
- Date: Tue Jan 18 16:51:05 2022 +0800
- 指针分离
- commit 6571e1ad805767222f3e083f389e0ebeb7769ad5 (origin/dev)
- Author: Stronger <231@qq.com>
- Date: Mon Sep 13 09:24:05 2021 +0800
- 初始化文件
切回master 执行git log
- commit 4fe2e28e0511bbae2dd210698092980c61bf62bc (HEAD -> master, origin/master, origin/HEAD)
- Author: Stronger <231@qq.com>
- Date: Tue Jan 18 16:31:39 2022 +0800
-
- 第二次提交
-
- commit 6571e1ad805767222f3e083f389e0ebeb7769ad5 (origin/dev)
- Author: Stronger <231@qq.com>
- Date: Mon Sep 13 09:24:05 2021 +0800
-
- 初始化文件
在分离头指针下当执行git checkout 到其他分支时,会收到下面的警告,提示用户要新创建一个分支来保留做的修改
- Warning: you are leaving 1 commit behind, not connected to
- any of your branches:
-
- 4f544b3 指针分离
-
- If you want to keep it by creating a new branch, this may be a good time
- to do so with:
-
- git branch <new-branch-name> 4f544b3
-
- Switched to branch 'master'
- Your branch is up to date with 'origin/master'.
分离头指针状态查看和返回
git status可以查看是否在头指针分离状态
- $ git status
- HEAD detached at 4f544b3
- nothing to commit, working tree clean
切换会master 再次查看
- $ git checkout master
- Already on 'master'
- Your branch is up to date with 'origin/master'.
-
- stronger@LAPTOP-SK1M3K9E MINGW64 /e/git/learngit (master)
- $ git status
- On branch master
- Your branch is up to date with 'origin/master'.
-
- nothing to commit, working tree clean
特点:HEAD 总是指向当前分支上最近一次提交记录
场景:有时候我们不想为某次的修改单独创建一个分支,也没有想要提交到版本库的意思,只是做下调试,那么我们就可以使用git提供的分离头指针方法。如果发现真的有必要提交到版本库,还可以使用git checkout -b
命令来为这次的提交新建一个分支,再把分支合并上去。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。