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


当前回答

我遇到了这样一个场景,我签出了本地更改,但没有提交或存储它们。据我所知,没有任何命令能帮助我。对我有用的是CTRL+Z。

CTRL + Z

偶然的机会,我所有的文件都在编辑器中打开,所以在编辑器中,我只需按CTRL+Z所需的文件,这解决了我的问题

PS:我用的是Sublime文本编辑器。

其他回答

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

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

根据定义,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重置——很难,总有一天会有回报的。

答案来自这个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}

你的好日子回来了!:)

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

我运行了git reset -hard origin/master

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

这招对我很管用:

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

对于那些丢失了未分期和未提交更改的VSCode用户

这只会工作,如果你没有广泛编辑您的文件后再次重置。

尝试在VSCode中撤销文件更改

我确实进行了重置——当我的利益相关者决定在我构建功能时重新定义功能时,这很困难。一小时后,同样的利益相关者改变了主意。

我休息了一会儿又回来了。当我看到他们改变主意后,我决定尝试撤销我正在处理的文件,它成功了!我设法拿回了所有的作业。