git reset --hard
往往用来移动 HEAD 指针,但这样会导致 commit 的内容被删除,往往后悔不已。
可以通过reflog来进行恢复,前提是丢失的分支或commit信息没有被git gc清除,一般情况下gc对那些无用的object会保留很长时间后才清除的
可以使用git reflog
或git log -g
命令来看到所有的操作日志。你执行的每一条git指令都有迹可循,而且可以回退到任意一步。可谓回滚操作中的万能钥匙了。
chenshang@bogon:~/learn/gitk [master]$ git reflog
baf1722 HEAD@{0}: reset: moving to baf1722
add2e4e HEAD@{1}: reset: moving to HEAD^
f6df0e4 HEAD@{2}: reset: moving to HEAD^^
baf1722 HEAD@{3}: reset: moving to baf1722
f6df0e4 HEAD@{4}: reset: moving to HEAD^^
baf1722 HEAD@{5}: merge feture/f2: Merge made by the 'recursive' strategy.
0f02b7a HEAD@{6}: merge feture/f1: Merge made by the 'recursive' strategy.
f6df0e4 HEAD@{7}: checkout: moving from feture/f2 to master
3e54d52 HEAD@{8}: commit: 5
5465608 HEAD@{9}: checkout: moving from feture/f1 to feture/f2
0f4153e HEAD@{10}: commit: 4
add2e4e HEAD@{11}: checkout: moving from master to feture/f1
f6df0e4 HEAD@{12}: merge feture/f2: Merge made by the 'recursive' strategy.
add2e4e HEAD@{13}: merge feture/f1: Fast-forward
1195d28 HEAD@{14}: checkout: moving from feture/f2 to master
5465608 HEAD@{15}: commit: 3
1195d28 HEAD@{16}: checkout: moving from master to feture/f2
1195d28 HEAD@{17}: checkout: moving from feture/f1 to master
add2e4e HEAD@{18}: commit: 2
1195d28 HEAD@{19}: checkout: moving from master to feture/f1
1195d28 HEAD@{20}: commit: 1
9cb291d HEAD@{21}: commit (initial): 0
恢复的过程很简单
- 通过
git log -g
或git reflog
命令来找到需要恢复的信息对应的 commitid,可以通过提交的时间和日期来辨别, - 找到对应的commitid
- 通过
git branch recover_branch commitid
来建立一个新的分支
这样,就把到commitid为止的代码、各种提交记录等信息都恢复到了recover_branch分支上了。