1.HEAD基礎
git checkout 實際上是修改HEAD檔案的內容,讓其指向不同的branch。
HEAD檔案指向的branch就是當前branch.
一般來講,HEAD的內容是指向staging(暫存區)的master檔案的。
ref: refs/heads/master
當然也可指向其他索引檔案,不管怎麼樣,這個索引檔案的內容又由git reset控制。
通過git branch命令看到的結果和HEAD檔案內容一致。
$ git branch -v* master 1aea8d9 [ahead 1] add test file x
2.最簡單用法
git checkout最簡單的用法,顯示工作區,暫存區和HEAD的差異:
$ git checkoutMxYour branch is ahead of 'origin/master' by 1 commit.
意思是我本地倉庫比遠程倉庫領先一個提交操作。git checkout HEAD 功能相同。
如果用-a 參數,可以看到很多branch,包括遠端branch,比如:
git branch -a* master remotes/origin/HEAD -> origin/master remotes/origin/develop remotes/origin/issue_193 remotes/origin/issue_210 remotes/origin/master
3.detached HEAD
如果讓HEAD檔案指向一個commit id,那就變成了detached HEAD。git checkout 可以達到這個效果,用下面的命令:
git checkout 1aea8d9^
laea8d9是最近的一次commit id,^指的是之前一次,因此上面的操作結果是讓HEAD檔案包含了倒數第二次提交的id.
下面示範如何進入datached HEAD狀態,並恢複回來。
$ git branch -v* master 89f8dae [ahead 2] update x$ git checkout 89f8dae^Note: checking out '89f8dae^'.You are in 'detached HEAD' state. You can look around, make experimentalchanges and commit them, and you can discard any commits you make in thisstate without impacting any branches by performing another checkout.If you want to create a new branch to retain commits you create, you maydo so (now or later) by using -b with the checkout command again. Example: git checkout -b new_branch_nameHEAD is now at 1aea8d9... add test file x
好,現在恢複回來。
$ git checkout masterPrevious HEAD position was 1aea8d9... add test file xSwitched to branch 'master'Your branch is ahead of 'origin/master' by 2 commits.
我並不清楚detached HEAD有何實際用處,反正就是一個讓HEAD隨便指向某個commit id,而不在乎是哪個branch的功能。