Recover from git reset --hard?

2018-12-31 10:29发布

Is there any way to recover uncommitted changes to the working directory from a git reset --hard HEAD?

标签: git
19条回答
零度萤火
2楼-- · 2018-12-31 10:51

Yes, YOU CAN RECOVER from a hard reset in git.

Use:

git reflog

to get the identifier of your commit. Then use:

git reset --hard <commit-retrieved-using-reflog>

This trick saved my life a couple of times.

You can find the documentation of reflog HERE.

查看更多
冷夜・残月
3楼-- · 2018-12-31 10:51

If you luckily had the same files opened on another editor (eg. Sublime Text) try a ctrl-z on those. It just saved me..

查看更多
谁念西风独自凉
4楼-- · 2018-12-31 10:54

This is what I usually do if I lose some changes.

git reflog
git checkout <commit id> // now you are in where you want but you cannot push from detached branch to master
manually copy and paste changes from detached branch to master or working branch
git reset --hard HEAD // if needed
git add ... > git commit ... > git push ...

to move the pointer back to your previous commits but keeping the changes you made so far in your latest commits checkout git reset --soft dadada

查看更多
初与友歌
5楼-- · 2018-12-31 10:56

When we do git reset --hard and all local uncommited changes is deleted. To recover back the changes - in IDE click on the file, compare the file with Local history which will list changes as per date and we can recover the data. Your day is saved!

查看更多
明月照影归
6楼-- · 2018-12-31 10:57

I found out the hard way that any uncommitted files before a git reset --hard <commit> gets removed from git history. However, I was lucky enough to have kept my code editor session open during the entire time I was pulling my hair out, that I discovered that a simple control + z in each of the affected files returned the state of the file back to the version before Git so obligingly reset everything I didn't ask it to specifically. Hooray!!

查看更多
时光乱了年华
7楼-- · 2018-12-31 10:59

While I was working on a local project, I wanted to move it to GitHub and then created a new repository. While I was trying to add all these files to the new repository with .gitignore, I accidentally added a wrong file and then tried to clear it.

I ran git reset --hard origin/master :P

Then all of my local files deleted because the repo was empty. I thought everything was gone.

This saved my life:

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

Hope it saves another life.

查看更多
登录 后发表回答