git reset--hard后恢复暂存区文件

xiaoxiao2021-02-28  13

最近使用git时,遇到了一个问题,还是自己用的不6,,本来想把pom.xml文件直接replace掉,结果把所有文件都替了,导致原先缓存区里(只add,没有commit)的文件全部被还原了,当时还没在意,心想用reflog,再reset就好了,特么后来才想起来,都没COMMIT,根本没法弄呀,网上查了不少资料都是COMMIT以后的,我这个只进行了ADD操作,急坏了。。后来查询到了几个命令,没想到还真恢复了

git reset --hard 是把本地库里的文件全部替换到了工作空间里

下面是stackoverFlow上一些人提供的方法

If you didn't already commit your local changes (or at least stage them via `git add`, they're gone. `git reset --hard` is a destructive operation for uncommitted changes. If you did happen to stage them, but didn't commit them, try `git fsck --lost-found` and then search through the contents of .git/lost-found - it will contain all of the objects that aren't referenced by a known commit, and may include versions of files that were staged. You can recover anything you git added, with git fsck --lost-found and poke around in .git/lost-found. find .git/objects -type f | xargs ls -lt | sed 60q will give you the last 60 things to get added to the repo, that'll help. Anything you didn't git add is gone as surely as if you'd deleted it yourself.

执行 find .git/objects -type f | xargs ls -lt | sed 60q ,这里60q 的意思是最近60次的add,然后会出来:

$ find .git/objects -type f | xargs ls -lt | sed 60q

-r—r—r— 1 Y Administ 222 Feb 3 21:00 .git/objects/02/18fb7591

36a0ee550d2e4d179f01bd75af48a0

-r—r—r— 1 Y Administ 176 Feb 3 21:00 .git/objects/5c/cb94ce63

fd5196db10dffa6bab149c8b30546e

-r—r—r— 1 Y Administ 77 Feb 3 21:00 .git/objects/d5/177a8da3

96b5d6450d2c8e6ecf2f3ad8e41cd2

-r—r—r— 1 Y Administ 1387 Feb 3 21:00 .git/objects/e0/7e9099c0

b27a4dd1a432db0bbf2112ca544ebd

-r—r—r— 1 Y Administ 5480 Feb 3 20:38 .git/objects/74/ea02bfa7

353be6095959503abdd7dc0a178f53

-r—r—r— 1 Y Administ 2701 Feb 3 20:38 .git/objects/7a/d366bac4

91f6793d9b7da0cc3e7fb5ba26d403

-r—r—r— 1 Y Administ 2597 Feb 3 20:38 .git/objects/a7/9c139160

fa387b365629ead63f5818177d2e48

此处仅仅截取一部分信息,然后就是恢复了。

使用 git cat-file -p ID > a.md ,解释一下这个命令,就是将ID所示的文件读取出来重定向保存到 a.md 文件内,ID是objects后面的一串东西,比如第一个就是 0218fb759136a0ee550d2e4d179f01bd75af48a0 。(PS:需要将之间的/ 去掉)。恢复的文件就在项目目录里a.md中,这样缓存区的文件就回来了,至于连add都没有的同学。。
转载请注明原文地址: https://www.6miu.com/read-1250174.html

最新回复(0)