版本回退
Git 的 commit 会保存一个快照,一旦文件改乱或误删文件,可以从最近一个 commit 恢复,然后继续工作。
先回顾下之前的 readme.txt 的几个版本:
-
版本1:wrote a readme file
Git is a version control system. Git is free software.
-
版本2:add distributed
Git is a distributed version control system. Git is free software.
-
版本3:append GPL
Git is a distributed version control system. Git is free software distributed under the GPL.
查看 git 的历史记录
执行 git log 命令查看历史记录:
$ git log
commit 1094adb7b9b3807259d8cb349e7df1d4d6477073 (HEAD -> master)
Author: Michael Liao <askxuefeng@gmail.com>
Date: Fri May 18 21:06:15 2018 +0800
append GPL
commit e475afc93c209a690c39c13a46716e8fa000c366
Author: Michael Liao <askxuefeng@gmail.com>
Date: Fri May 18 21:03:36 2018 +0800
add distributed
commit eaadf4e385e865d25c48e7ca9c8395c3f7dfaef0
Author: Michael Liao <askxuefeng@gmail.com>
Date: Fri May 18 20:59:18 2018 +0800
wrote a readme file
- git log 命令显示从最近到最远的提交日志,最新的记录后的 HEAD 表示当前版本;
- HEAD 表示当前版本,HEAD^ 表示上一个版本,HEAD^^ 表示倒数第三个版本;当太多是用 HEAD~n 表示,例如 HEAD~100 表示上100个版本。
- 可以使用 –pretty=oneline 减少输出信息;
$ git log --pretty=oneline 1094adb7b9b3807259d8cb349e7df1d4d6477073 (HEAD -> master) append GPL e475afc93c209a690c39c13a46716e8fa000c366 add distributed eaadf4e385e865d25c48e7ca9c8395c3f7dfaef0 wrote a readme file
- 信息中 commit 后面的字符串是 commit_id(版本号,通过 SHA1 计算出来的数字,用十六进制表示),Git 会把它们自动串成一条时间线。后面将详解。
通过命令回退版本
执行 git reset 回退版本:
git reset --hard HEAD^
HEAD is now at e475afc add distributed
- –hard 的意义后面详解。
执行 cat 命令查看一下:
$ cat readme.txt
Git is a distributed version control system.
Git is free software.
执行 git log 再看现在版本库的状态:
$ git log
commit e475afc93c209a690c39c13a46716e8fa000c366 (HEAD -> master)
Author: Michael Liao <askxuefeng@gmail.com>
Date: Fri May 18 21:03:36 2018 +0800
add distributed
commit eaadf4e385e865d25c48e7ca9c8395c3f7dfaef0
Author: Michael Liao <askxuefeng@gmail.com>
Date: Fri May 18 20:59:18 2018 +0800
wrote a readme file
到此,会有一个问题;版本 append GPL 看不到了,起始可以通过 commit_id 找回来;
执行 git reset --hard commit_id,版本号可以不写全:
$ git reset --hard 1094a
HEAD is now at 83b0afe append GPL
再看readme.txt的内容,内容已经还原:
$ cat readme.txt
Git is a distributed version control system.
Git is free software distributed under the GPL.
查看 git 执行的每次命令
若是回滚后,忘记上一次的 commit_id 导致无法恢复,怎么办。
执行 git reflog 查看每次的执行的命令:
$ git relog
e475afc HEAD@{1}: reset: moving to HEAD^
1094adb (HEAD -> master) HEAD@{2}: commit: append GPL
e475afc HEAD@{3}: commit: add distributed
eaadf4e HEAD@{4}: commit (initial): wrote a readme file
Git 滚动机制分析
Git 的版本回滚速度非常块,因为 Git 在内部有一个指针向当前版本的 HEAD 指针,当回退版本时,Git 仅需要把 HEAD 从 append GPL 指向 add distributed 即可