Undo git reset without any commits yet

拈花ヽ惹草 提交于 2021-01-28 03:43:34

问题


I recently wanted to, as I thought, update my code on the remote git repository. I didn't realize it's not even committed yet. I did create some errors, so I wanted to reset the branch to its previous state.

As you may expect, I used git reset --hard.

Well, everything (the whole project) has been gone ever since; except the .gitignore files/folders, of course. I've been wondering, is there any way to undo that?

The only steps I did:

git add .
# Here I realized there is a bug in what I did
# I thought myself it would be better to undo that as it wasn't even something needed
git reset --hard 

Also, I'd like to point out it's probably not a duplicate of any question here as others have had some commits before. That's completely new repository, and it's been "reset hard".


回答1:


You can resurrect the files at the state you added them, but without their file name. With git fsck you get a list of files which are not referenced by any commit.

$ git fsck
Checking object directories: 100% (256/256), done.
Checking objects: 100% (1/1), done.
dangling blob c7c49b553f1b8c3c8f7955780e5dfdb934ce26db
dangling tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904
dangling blob 4f92ab465171608a2c713f2f5439143df2c8afc9
dangling blob 9c1216eb500c0fc2c55c263a9cf221f282c3cd7b

Then you can use git cat-file to get the file content:

for blob in `git fsck | grep 'dangling blob' | cut -d\  -f3` ; do git cat-file -p $blob > $blob ; done

Or you can also use git fsck --lost-found, which puts all dangling objects into .git/lost-found/



来源:https://stackoverflow.com/questions/48518040/undo-git-reset-without-any-commits-yet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!