分離頭指針


背景知識

detached HEAD state,分離頭指針,即HEAD指針直接指向提交記錄的情況
正常情況下,HEAD應指向某一分支
如果執行了git checkout tag名git checkout 遠端分支名git checkout 提交記錄哈希值,則HEAD會指向指向某一提交記錄,這就是detached HEAD state

實驗

先用git log和圖形化軟件git log查看一下開始實驗前test倉庫的提交記錄樹

$ git log
commit 314b5494eb06a9963f4e6f97075f2354c8a15f13 (HEAD -> master)
Author: MilesGO <164173218@qq.com>
Date:   Sun Jun 9 17:20:40 2019 +0800

    add main2.cpp

commit 12c2c80788dcd74a1cd739157c0a1011514d36b2
Author: MilesGO <164173218@qq.com>
Date:   Sun Jun 9 17:11:48 2019 +0800

    add src/main.cpp

commit 4a1d75425a4cd5c3e206a4c69415c59802175039
Author: MilesGO <164173218@qq.com>
Date:   Sun Jun 9 17:00:08 2019 +0800

    modify README

commit 29c07152991c7b3ee41f9cb5ac1eff1f26610665
Author: MilesGO <164173218@qq.com>
Date:   Sun Jun 9 16:52:41 2019 +0800

    add README

用git-fork查看之后,可以看到整棵提交記錄樹是線性的
我們直接用哈希值檢出到倒數第二次提交

$ git checkout 12c2c8
Note: checking out '12c2c8'.

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 performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at 12c2c80 add src/main.cpp

翻譯一下上面的內容,您正處於分離頭指針狀態,你可以做一些實驗性的改動並且提交它們,但是這些提交都會被丟棄,除非你用一個分支指向它們
當前這個分支下還沒有main2.cpp文件,我們添加這個文件

$ echo 'hello world again' >> main2.cpp
$ git add main2.cpp
$ git commit -m 'add main2.cpp again'
[detached HEAD 11ed7f1] add main2.cpp again
 1 file changed, 1 insertion(+)
 create mode 100644 main2.cpp

$ git checkout master
Warning: you are leaving 1 commit behind, not connected to
any of your branches:

  11ed7f1 add main2.cpp again

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> 11ed7f1

Switched to branch 'master'

翻譯一下上面的內容,你把1個未用分支指向的提交記錄給落掉了,其哈希值為11ed7f1,如果你想要保留這個提交,則請用git branch <new-branch-name> 11ed7f1指令創建1個新的分支並指向這個提交記錄

$ git branch -av
* master 314b549 add main2.cpp

git branch pick 11ed7f1

$ git branch -av
* master 314b549 add main2.cpp
  pick   11ed7f1 add main2.cpp again
  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM