recovering from git reset –hard

You’ve been there … you’ve done some work, then staged or committed it in git and forgotten about it for a bit. Only to hop into the terminal another day thinking you’re on master and wondering why your git pull is doing a merge.

Having neither the time, or patience since you’re running low on coffee and you want to look at that Pull request locally, you’ve run

git reset --hard origin/master

only to instantly remember you’ve blown away all that good work.

The good news is, you can recover from git reset error in very specific instances as described here

I accidentally ran git reset --hard on my repo today too while having uncommitted changes too today. To get it back, I ran git fsck --lost-found, which wrote all unreferenced blobs to <path to repo>/.git/lost-found/. Since the files were uncommitted, I found them in the other directory within the <path to repo>/.git/lost-found/. From there, I can see the uncommitted files, copy out the blobs, and rename them.

Note: This only works if you added the files you want to save to the index (using git add .). If the files weren’t in the index, they are lost.

In the case (like mine) where you committed the changes previously, you will find hashes in .git/lost-found/commit that refer to the commits that you lost. You can view what is in them by running

`git show 98b9e853c9c8ffc07b450c61b05313cc4aa9eceb` (for example)

Usually it will just show the diff of the commit which you can re-apply manually line by line, other times you’ll see something like this

commit 98b9e853c9c8ffc07b450c61b05313cc4aa9eceb
Merge: c5060f1 89e959d
Author: xxxxxx <xxx@xxxxxx.com>
Date: Thu Jul 13 17:42:09 2017 -0500

Merge branch ‘master’ of https://github.com/xx/xx xx/update-readme

on the line that says “Merge”. You can run a git show on one or both those hashes as they point to the parent commits of the one you’re looking at.
You can keep doing that till you get the commit you were looking for. whew!