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


当前回答

当我在做一个本地项目时,我想把它移动到GitHub上,然后创建一个新的存储库。当我试图用.gitignore将所有这些文件添加到新的存储库中时,我不小心添加了一个错误的文件,然后试图清除它。

我运行了git reset -hard origin/master

然后我所有的本地文件都被删除了,因为回购是空的。我以为一切都消失了。

这招对我很管用:

git reflog show
git reset HEAD@{1} 
git push 

其他回答

如果你幸运地有相同的文件打开在另一个编辑器(例如。Sublime Text)试试按ctrl-z键。它救了我。

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

如果你使用的是(最近的)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重置——很难,总有一天会有回报的。

如果你使用IntelliJ:

在上下文菜单中,选择“本地历史记录”,单击子菜单上的“显示历史记录”:

项目或文件夹的本地历史视图会显示所有内容 你在过去几天所做的一切。的操作列中 在对话框的下半部分,选择要滚动的动作 回来。[…这样做,对话框的上部显示了更改文件的树状视图。如果您只想恢复已删除的文件,而不考虑此后所做的其他更改,您可以在树视图中选择文件Lost.txt,然后单击Revert按钮。

http://blog.jetbrains.com/idea/2008/01/using-local-history-to-restore-deleted-files/

这把我救了出来!

信息丢失了。

由于您没有提交,您的.git从未存储此信息。所以基本上git不能为你恢复它。

但是,如果你只是使用git diff,有一种方法可以通过以下3个简单步骤使用终端输出恢复。

滚动你的终端并寻找git diff的o/p,将o/p保存在一个名为diff.patch的文件中 搜索并替换所有7个空格和8个空格与制表符(\t)字符,并保存更改。 进入git存储库。应用diff.patch (patch -p1 < diff.patch)

注意:当您将数据从终端复制到文件时,要小心并清楚地看到数据是连续输出的,不包含任何冗余数据(由于按下向上和向下箭头)。否则你会搞砸的。