精华 在 git 中找回丢失的 commit
发布于 9 年前 作者 alsotang 11225 次浏览 最后一次编辑是 8 年前 来自 分享

今晚跟我老板 @fish 一起发布新代码的时候,遇到了一件蛋疼的事情,git 的 commit 丢了。 本来大家都准备发完代码走人了,已经更新了那么四五条 commit。可是在 rebase 的时候手抖,把这几条 commit 遗失了。

然后上网找,找到了一个 git fsck --lost-found 的命令,这个命令的命名还蛮有意思的,fsck。它的作用是从 git 的垃圾堆里面找到那些被丢弃的 commit。 这个命令是没有副作用的,大家可以在自己的 git 目录下试试:

untitled1.png

于是乎我们就得到了一堆的 commit,可这些 commit 的排序很诡异,既不是按提交时间排序,也不是按 commit 的 hash 字符序排序,我感觉是乱序的。 然后我们就深感蛋疼。 我们一开始用 git show 这个命令一点点地在看哪些是我们要的 commit

后来发现,其实每次 git show 的时候,输出字符里面是有时间的

untitled3.png

于是我们写了个小脚本,找出哪些输出中有今天的时间,就轻易找回了我们要的 commit。 相应脚本如下:

var exec = require('child_process').exec;

exec('git fsck --lost-found', function (err, out) {
 out.split('\n').forEach(function (row) {
   var commit = row.split(/\s+/)[2];
   exec('git show ' + commit, function (err, out) {
     if (out.indexOf('Nov 20') !== -1) {
       console.log(commit);
     }
   });
 });
});


6 回复

干货!用git reflog 应该也能找回,不过没试过。。

reflog 直接上

逼格不够高。。。

git fsck --lost-found 2&>/dev/null | while read i; do; git show `echo $i | cut -d ' ' -f 3` | head -n 6; done

@xingrz 不会 shell…T T

@jiyinyiyong @xingrz @ruanyl 确实应该用 reflog 的。。

这样简单了一些, show的输出可以自定义,所以

git fsck --lost-found  | grep commit | awk '{print $3}' | xargs -I {} git log --pretty=format:"%h %cd" {} | do_what_you_need
回到顶部