Git is God – what to do if you’ve deleted a commit

You can accidentally delete a commit in many ways – yeah! that’s pretty easy – you just have to do one thing – not pay attention to what you are doing! And boom! you’ve deleted a commit.

In my case, I was rewriting my local commit history before sending a patch. I was using –
[sourcecode language=”shell” gutter=”false”]
git rebase -i
[/sourcecode]

I needed to delete an unnecessary commit but I accidentally deleted the commit on which I was working upon. That was a tight spot. I had 2 files full of changes!
So, now let me enlighten you on the power of Git.
You do a –
[sourcecode language=”shell” gutter=”false”]
git fsck –lost-found
[/sourcecode]
It will show a list of commit ids. In my case I had the commit id (by scrolling upward in the terminal) and it was there in that list of commit ids.
To be sure if that’s the correct commit, you can check it using –
[sourcecode language=”shell” gutter=”false”]
git show
[/sourcecode]
Then I did –
[sourcecode language=”shell” gutter=”false”]
git cherry-pick <commit_id>
[/sourcecode]
I had multiple such dangling commits. Hence I used cherry-pick. You can get back your work through a lot of other ways – e.g. by using –
[sourcecode language=”shell” gutter=”false”]
git rebase <commit_id>
[/sourcecode]
or
[sourcecode language=”shell” gutter=”false”]
git merge <commit_id>
[/sourcecode]