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


当前回答

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

如果你使用的是(最近的)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?

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

其他回答

如果您正在Netbeans上开发,请查看文件选项卡和文件编辑区域之间的内容。这里有“来源”和“历史”。在“历史记录”中,你会看到使用版本控制(git/other)所做的更改,但也有本地所做的更改。在这种情况下,局部更改可以拯救您。

根据定义,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重置-困难和丢失了所有未提交的更改。幸运的是,我使用了一个编辑器(IntelliJ),我能够从本地历史记录中恢复更改。Eclipse应该允许您做同样的事情。

答案来自这个SO

$ git reflog show

4b6cf8e (HEAD -> master, origin/master, origin/HEAD) HEAD@{0}: reset: moving to origin/master
295f07d HEAD@{1}: pull: Merge made by the 'recursive' strategy.
7c49ec7 HEAD@{2}: commit: restore dependencies to the User model
fa57f59 HEAD@{3}: commit: restore dependencies to the Profile model
3431936 HEAD@{4}: commit (amend): restore admin
033f5c0 HEAD@{5}: commit: restore admin
ecd2c1d HEAD@{6}: commit: re-enable settings app

# assuming you want to get back to 7c49ec7 (restore dependencies to the User model)

$ git reset HEAD@{2}

你的好日子回来了!:)

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

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