目录
分离头指针
一、分离头指针演示
1、指令
git checkout commitHash
2、指令演示
#查看下git的提交记录
localhost:firstProject LC$ git log
commit 666fb34b3499cb2937178fc246432e5bfaef6f43 (HEAD -> dev, tag: js01, master)
Author: LC <LC@163.com>
Date: Tue Dec 22 16:10:23 2020 +0800
modified index.html
commit dee94861245b0ea5119d1c19e6939cfa381e5bf0
Author: LC <LC@lakala.com>
Date: Tue Dec 22 14:01:37 2020 +0800
add index and images
#通过checkout 分离头指针
localhost:firstProject LC$ git checkout dee94861245b
Note: switching to 'dee94861245b'.
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 dee9486 add index and images
localhost:firstProject LC$
git提示:
当前处于分离头指针的状态,不属于任何一个分支,但在该状态下可以更改并提交commit
也可以通过切换到分支来丢弃提交的commit
如果想保留你创建的提交,可以通过switch命令中使用 -c 来实现
git switch -c <new-branch-name>
当我们切换到分支时
localhost:firstProject LC$ git checkout master
Warning: you are leaving 1 commit behind, not connected to
any of your branches:
73f93ec Add testpng
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> 73f93ec
Switched to branch 'master'
从提示可以看出,已经切换到了master分支,但此时我们仍然可以找回在分离头指针的提交记录,根据提示使用以下命令
localhost:firstProject LC$ git branch -av
dev 666fb34 modified index.html
* master 666fb34 modified index.html
newBran e6b3c52 head detached test
localhost:firstProject LC$ git branch fix_branch 73f93ec
通过gitk我们来看下我们现在拥有的分支情况
localhost:firstProject LC$ gitk --all
虽然切换分支后我们找回了在分离头指针时的commit记录,但这样是很危险的,没有绑定具体分支的提交很可能会被git当做垃圾丢掉,所以若想保存自己的提交请绑定到具体的分支
二、分离头指针的作用
当我们需要尝试做一些东西的时候,可以使用分离头指针,
如果最终发现结果不理想可以直接切换到其它分支丢弃提交
如果最终发现结果是我们想要的可以创建一个新的分支来保存我们的提交
进一步理解HEAD和branch
一、HEAD与branch、commit的关系
HEAD不仅可以指向某个分支,还可以指向某次具体的commit(分离头指针状态),
但当HEAD指向某个分支时,也是指向这个分支的最后一次commit
二、HEAD的作用
比如当我们新建一个分支时,可以使用下面的命令
localhost:firstProject LC$ git checkout -b fix_css master
Switched to a new branch 'fix_css'
如果此时HEAD指向master分支,我们就可以使用
localhost:firstProject LC$ git checkout -b fix_css HEAD
Switched to a new branch 'fix_css'
或者我们查看某两次commit的不同时
localhost:firstProject LC$ git diff 666fb34b3499cb dee94861245
如果此时HEAD指向666fb34b3499cb
localhost:firstProject LC$ git diff HEAD dee94861245
或者还可以这样使用,来表示HEAD与(HEAD^)HEAD的father的不同
git diff HEAD HEAD^
HEAD^ 与 HEAD~1 相同
HEAD^^ 与 HEAD~2 相同
行者常至,为者常成!