有没有办法从git重置中恢复未提交的更改到工作目录-hard HEAD?


当前回答

根据定义,git reset -hard会丢弃未提交的更改,git无法恢复它们(你的备份系统可能会有帮助,但不是git)。

实际上,很少有git重置的情况——困难是个好主意。在大多数情况下,有一个更安全的命令来做同样的事情:

If you want to throw away your uncommitted changes, then use git stash. It will keep a backup of these changes, which will expire after some time if you run git gc. If you're 99.9% sure you'll never need these changes back, then git stash is still your friend for the 0.1% case. If you're 100% sure, then git stash is still your friend because these 100% have a measurement error ;-). If you want to move your HEAD and the tip of the current branch in history, then git reset --keep is your friend. It will do the same thing as git reset --hard, but will not discard your local changes. If you want to do both, then git stash && git reset --keep is your friend.

教你的手指不要使用git重置——很难,总有一天会有回报的。

其他回答

一般来说,您无法返回未提交的更改。

以前的分段更改(git add)应该可以从索引对象中恢复,所以如果你这样做了,使用git fsck——lost-found来定位与它相关的对象。(这将对象写到.git/lost-found/目录;从那里你可以使用git show <filename>来查看每个文件的内容。)

如果没有,答案是:看看你的备份。也许你的编辑器/IDE将临时拷贝存储在/tmp或C:\ temp之类的目录下

git reset HEAD@{1}

这将恢复到前一个HEAD

[1] vim例如,可选地存储持久撤销,eclipse IDE存储本地历史;这样的功能可能会节省你的**

嗯,据我所知,最好的解决方案是使用IDE特性。

选择丢失文件的存储库,并右键单击它 在菜单>中查找本地历史显示历史 现在检查版本版本,你所有的文件都存在>,选择它,然后点击恢复。 这就是最可能的情况。

注意:上述解决方案适用于在任何IDE(如intelliJ)中进行更改或导入存储库。

我不小心运行git重置-对我的回购今天也很难,而今天也有未提交的更改。为了找回它,我运行git fsck——lost-found,它将所有未引用的blobs写入<path To repo>/.git/lost-found/。由于文件未提交,我在<路径repo>/.git/lost-found/的另一个目录中找到了它们。从那里,我可以使用git show <filename>看到未提交的文件,复制出blob,并重命名它们。

注意:只有当你将想要保存的文件添加到索引中时(使用git add .),这才有效。如果文件不在索引中,就会丢失。

(适用于部分用户的答案)

如果你使用的是(最近的)macOS,即使你没有使用时间机器磁盘,操作系统也会每小时保存一次备份,称为 当地的快照。

进入时间机器,导航到你丢失的文件。操作系统会问你:

The location to which you're restoring "file.ext" already contains an
item with the same name. Do you want to replace it with the one you're
restoring?

你应该能够恢复你丢失的文件。

根据定义,git reset -hard会丢弃未提交的更改,git无法恢复它们(你的备份系统可能会有帮助,但不是git)。

实际上,很少有git重置的情况——困难是个好主意。在大多数情况下,有一个更安全的命令来做同样的事情:

If you want to throw away your uncommitted changes, then use git stash. It will keep a backup of these changes, which will expire after some time if you run git gc. If you're 99.9% sure you'll never need these changes back, then git stash is still your friend for the 0.1% case. If you're 100% sure, then git stash is still your friend because these 100% have a measurement error ;-). If you want to move your HEAD and the tip of the current branch in history, then git reset --keep is your friend. It will do the same thing as git reset --hard, but will not discard your local changes. If you want to do both, then git stash && git reset --keep is your friend.

教你的手指不要使用git重置——很难,总有一天会有回报的。