Kevin Kevin - 1 month ago 9
Git Question

Recover files after bad git reset --hard command

This one is going to take an expert:

I ran a

git init
and
git add --all
and a new project I worked on for way too long before I realized I hadn't setup the git repot. After running the git add I realized I forgot to create an .gitignore file. Without thinking I ran
git reset --hard HEAD
and OH NO all my files are gone, there's no log or reflog, no status and all commands result in
fatal: bad default revision 'HEAD'
. I'm sure the answer is that I'm screwed. Can't seem to do anything with any of the dangling blobs, etc. Hoping some guru out there knows something I don't.

git fsck --full git:master
notice: HEAD points to an unborn branch (master)
Checking object directories: 100% (256/256), done.
notice: No default references
dangling blob c57eff55ebc0c54973903af5f72bac72762cf4f4
dangling blob 4740a6ee5099aa087bac317337e28bba78c4b83c
missing tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904
dangling blob 0d6b3be3e5517a7a7df7df941a6bd3740fcfc5e1
dangling blob d0437745b1902b1ec7e4154a6c058a900575ae7b
dangling blob 5223f05f29bed36037a68f1185f0d718f2a5f9b8
dangling blob d3f186be7e3fcac86aa15c6ebf416f636269f356
dangling blob 526b432e210b3a943df9a7146a0fb4c3e30fc2f5
dangling blob 96722f502f9bd93e5205ea07d8c9b56b11f2e9bd
dangling blob 594eff1d8bfd71561f4f9a0b1447c764e812e2aa
dangling blob df1b87ad781e0a961648f2c01d37b9fe15e581bd
dangling blob e196d0eaf4df52ec1d65faf1971e444d37640284
dangling blob a112aeec073daabfa02ba34b97f14a2bed7ff831
dangling blob e449375c07fc16d823fda51632ed0ed9894ff0f7
dangling blob 67d6eb75cb856092664d32c6eb9c10e1e226d61a
dangling blob abecf6b29f407556dc135523dd68d889d1e5147e
dangling blob af384fede44e1cf5dd963988a6aedf3161089891
dangling blob 2f21e52fb10e12a249ee3c99cf386fcf4a3bb08c
dangling blob f12933a0ea1ff0f052eef393485d59e5400f4d40
dangling blob 72f3fb0e59445ddf270882b4d323daee85d7fe2b
dangling blob f5bffa99c3301776fe0634ac7982c15320c46207
dangling blob fd764a7e888b3e090bdff5604576de1ab28e0ef8

Answer

You can still recover the content!

To be safe, first, do:

git fsck --lost-found

This will save the blobs to .git/lost-found/other

With the output of git fsck, you can now commands like

git show c57eff55ebc0c54973903af5f72bac72762cf4f4 > filename

to recover the files. This easily recovers the content, but not the filenames.

You can do this for all the blobs with a simple command like:

for blob in $(git fsck --lost-found | awk '$2 == "blob" { print $3 }'); do git cat-file -p $blob > $blob.txt; done

More details here - https://medium.com/@CarrieGuss/how-to-recover-from-a-git-hard-reset-b830b5e3f60c#.6grpr3abr