分离头指针情况下的注意事项

好的用处

如果临时想基于某个commit做变更,试试新方案是否可行,就可以采用分离头指针的方式。测试后发现新方案不成熟,直接reset回其他分支即可。省去了建、删分支的麻烦。

  1. 查看当前git提交的日志明细;

    MacBook-Pro-4:git_le booboo$ git log --oneline
    b4355e3 (HEAD -> master) add a.md&b.md
    f5634fd modify 20190406
    f223b4d add 20190403.md
    c4744d9 add readme.md
    MacBook-Pro-4:git_le booboo$ cat readme.md
    le
  2. 想在c4744d9的版本上测试某个修改动作;

    MacBook-Pro-4:git_le booboo$ git checkout c4744d9
    Note: checking out 'c4744d9'.

    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 c4744d9 add readme.md

    git提醒我们当前处于”detached HEAD”,即”分离头指针”的状态;HEAD当前指向c4744d9

  3. 修改文件readme.md

    MacBook-Pro-4:git_le booboo$ echo "detached HEAD" > readme.md
  4. 提交更改,并查看分支明细;

    MacBook-Pro-4:git_le booboo$ git branch -av
    * (HEAD detached at c4744d9) c4744d9 add readme.md
    master b4355e3 add a.md&b.md
    temp 49c201f temp_test
    MacBook-Pro-4:git_le booboo$ git add -A
    MacBook-Pro-4:git_le booboo$ git commit -m 'de'
    [detached HEAD 80718ad] de
    1 file changed, 1 insertion(+), 1 deletion(-)
    MacBook-Pro-4:git_le booboo$ git branch -av
    * (HEAD detached from c4744d9) 80718ad de
    master b4355e3 add a.md&b.md
    temp 49c201f temp_test
  5. 此时需要切换到主分支;

    MacBook-Pro-4:git_le booboo$ git checkout master
    Warning: you are leaving 1 commit behind, not connected to
    any of your branches:

    80718ad de

    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> 80718ad

    Switched to branch 'master'

    切换到master分支后,git提醒说可以通过命令git branch <new-branch-name> 80718ad创建一个分支,保存刚才的数据。

  6. 刚才测试的内容需要保存,则创建一个分支,否则不创建就丢弃了。

    MacBook-Pro-4:git_le booboo$ git branch de 80718ad
    MacBook-Pro-4:git_le booboo$ git branch -av
    de 80718ad de
    * master b4355e3 add a.md&b.md
    temp 49c201f temp_test

坏的情况