How to get your code back – Recover a dropped stash in Git

Have you dropped all of your code by mistake? The code was not checked in? Have you lost it forever? There is a way to get it back!

I have added two new classes inside of my projects (These have not been checked in and only exists on my local computer)

I now want to stash all of my code

I now drop all of my stash

The code has been removed from my local source control and is gone forever? (The steps below will help get it back)

Right click on the project folder and open it in ‘Git Bash’. (You can download Git for windows by searching online)

Add the lines below into the command window:

git fsck | awk '{print $3}' > tmp.txt
cat tmp.txt | xargs git show > tmp2.txt

Once this has been done you will see a tmp.txt and tmp2.txt in the folder directory

Open the tmp2.txt and find the nearest top commit in the text file.

Add the line below into the command window and replace the <commit id> with the id you find in the tmp2.txt file.

git stash apply <commit id>

Once that has been complete you can add the line below as well:

rm tmp.txt tmp2.txt

The code is back in source control!

Leave a Reply

Your email address will not be published. Required fields are marked *