初始狀態:git
執行命令:this
$ git checkout testing
這條命令作了兩件事。 一是使 HEAD 指向 master 分支,二是將工做目錄恢復成 master 分支所指向的快照內容。spa
$ git checkout -b iss53
這條命令是下面兩條命令的簡寫:指針
$ git branch iss53 $ git checkout iss53
現有一個倉庫,當前在 master 分支上,有三次提交記錄:code
$ git log --graph --all --oneline --decorate * 2950c9d (HEAD -> master) c * a61ae27 b * 1ef09c2 a
當你想作一些嘗試性的更新,而且可能隨時丟棄新增的代碼時,能夠將倉庫處於分離頭指針狀態下。例如,我想在提交 b(a61ae27)基礎下作試驗:orm
$ git checkout a61ae27 Note: checking out 'a61ae27'. 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 a61ae27... b
查看分支列表,HEAD 指向了提交 b(a61ae27),處於分離頭指針狀態:blog
$ git branch * (HEAD detached at) master
而後修改代碼,而且添加到暫存區和提交它,此時 HEAD 指向了提交 d(d605ebb):get
$ git log --graph --all --oneline --decorate * d605ebb (HEAD) d | * 2950c9d (master) c |/ * a61ae27 b * 1ef09c2 a
要注意的是,此時是沒有任何東西正在引用提交 d(d605ebb),若是你此時切換到其餘分支,那麼這部分修改的代碼會被 Git 垃圾回收。it
若是你對你的試驗滿意,那麼你能夠經過建立一個分支或者標籤指向提交 d(d605ebb)來保留修改的內容:io
$ git checkout -b foo
可是,若是你一不當心在新建分支以前切換了分支,使得修改的內容被 Git 回收了,也不用着急,能夠經過 reflog 指令來找回提交 d(d605ebb):
$ git checkout master Warning: you are leaving 1 commit behind, not connected to any of your branches: d605ebb d 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> d605ebb Switched to branch 'master'
其實你已經能夠根據 Git 給出的提示直接建立新分支了。
$ git reflog b990217 HEAD@{0}: checkout: moving from d605ebb783e029edb0193a6b6c9165c4e092462e to master d605ebb HEAD@{1}: commit: d a61ae27 HEAD@{2}: checkout: moving from master to a61ae27 2950c9d HEAD@{5}: commit: c a61ae27 HEAD@{6}: commit: b 1ef09c2 HEAD@{7}: commit (initial): a
最後執行如下命令便可:
$ git checkout -b foo
當你修改內容以後,卻又不想保留,就能夠使用如下命令來撤銷:
$ git checkout -- file.text
注意:要加上 -- 表示撤銷文件修改,來跟切換分支和分離頭指針作區分。