目的
學(xué)習(xí)如何檢出工作目錄中的先前快照。
在歷史中回憶很容易。checkout
命令將從倉庫復(fù)制任意快照到工作目錄。
$ git hist
注意:你記得在 .gitconfig
文件中定義的 hist
,對嗎?如果不是這樣,那么回顧一下有關(guān)別名的實(shí)驗(yàn)。
$ git hist
* 1f7ec5e 2013-04-13 | Added a comment (HEAD, master) [Jim Weirich]
* 582495a 2013-04-13 | Added a default value [Jim Weirich]
* 323e28d 2013-04-13 | Using ARGV [Jim Weirich]
* 9416416 2013-04-13 | First Commit [Jim Weirich]
檢查日志輸出,并找到第一個提交的哈希。它應(yīng)當(dāng)在 git hist
輸出的最后一行。在下面的命令中使用哈希碼(前 7 個字符就夠了)。然后檢查 hello.rb 文件的內(nèi)容。
$ git checkout <hash>
$ cat hello.rb
注意:這兒給的是 Unix 命令,適用于 Mac 和 Linux 系統(tǒng)。不幸的是,Windows 用戶必須換成他們的原生命令。
注意:許多命令都需要倉庫中的哈希值。因?yàn)槟愕墓V祵⑴c我的不同,當(dāng)你看到命令中的 <hash>
或 <treehash>
時(shí),使用你倉庫的正確哈希值替換。
你應(yīng)該看到:
$ git checkout 9416416
Note: checking out '9416416'.
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 9416416... First Commit
$ cat hello.rb
puts "Hello, World"
在 Git 中的“detached HEAD”信息意味著 HEAD (Git 跟蹤當(dāng)前目錄應(yīng)當(dāng)匹配的那部分)是直接指向提交而非分支。在你沒有切換到不同的分支時(shí),這種狀態(tài)只會記得已經(jīng)提交的更改。一旦你檢出了新的分支或標(biāo)簽,分離的提交將被丟棄 (因?yàn)?HEAD 已經(jīng)移走)。如果你想要保存在分離狀態(tài)的提交,那么你需要創(chuàng)建分支來記住提交。
Git 的舊版本將抱怨分離的 HEAD 狀態(tài)不在本地分支?,F(xiàn)在不用擔(dān)心這種情況。
注意 hello.rb 文件是最原始的內(nèi)容。
$ git checkout master
$ cat hello.rb
你應(yīng)該看到:
$ git checkout master
Previous HEAD position was 9416416... First Commit
Switched to branch 'master'
$ cat hello.rb
# Default is "World"
name = ARGV.first || "World"
puts "Hello, #{name}!"
master
是默認(rèn)分支的名稱。通過名稱檢出分支,你能夠回到該分支的最新版本。