撤销 git 操作

今天脑抽了一下,在做 git rebase -i 的时候无意识地把某一个 commit 给合并到前一个 commit 里去了,结果是该 commit 丢失,而且前一个 commit 也搞砸了。怎么能撤销这个操作呢?

Google 搜索了一下,发现了还有 git reflog 这个命令,可以查看 git 命令的历史记录,比如我刚才的操作:

324c85e HEAD@{0}: rebase -i (finish): returning to refs/heads/ipv6
324c85e HEAD@{1}: checkout: moving from ipv6 to 324c85e
324c85e HEAD@{2}: rebase -i (finish): returning to refs/heads/ipv6
324c85e HEAD@{3}: rebase -i (pick): ipv6: use xxxx
9fc8e64 HEAD@{4}: rebase -i (fixup): ipv6: unify xxxx
2ea2149 HEAD@{5}: rebase -i (fixup): updating HEAD
8d1f07b HEAD@{6}: checkout: moving from ipv6 to 8d1f07b
0e118d2 HEAD@{7}: commit: ipv6: separate xxxx

可以看出 HEAD@{7} 这个点就是我应该重置回去的,然后执行 git reset HEAD@{7} 就行了!

通过 git reflog 也可以撤销 git reset 的操作,非常实用。

另外,我很惊讶似乎还有不少人不知道 git rebase -i 这个命令。这个命令真的十分强大,我几乎天天都在用,它既可以用来合并补丁,也可以用来切割补丁,还能修改 commit 的记录(具体可自行参考 git-rebase 的手册),可以说是 git 命令中的一把瑞士军刀啊!不过如果你的 git tree 是 public 的,最好不用或者少用 git rebase,我用 git rebase 大多都是在自己的非 public 的树上。