Git: Recovering a lost stash

While using Git you'll probably end up using stash a lot, and if you do you'll probably end up losing a stash by mistake. Fear not, Git has ways of recovering lost stashes, or commits. For demonstration purposes, let's lose a stash.

First, I'll show some work in progress so that we know what we're recovering.

Work in progressWork in progress

Then let's stash these changes, followed by clearing the stash list. We've effectively lost the stash.

Losing the stash: git stash clearLosing the stash

Git provides a utility, fsck that can find unreachable commits:

git fsck --unreachable | grep commitLooking for unreachable commits

Now this is a lot of unreachable commits, we can find our lost stash with brute force by calling git show on each of these hashes, or to make our search a bit smarter we can grep for text that we know will be in the commit. For example: “Git is amazing”.

git fsck --unreachable | awk '/unreachable commit/ {print $3}' | xargs git show | grep -B 15 "Git is amazing" | grep commitFiltering results

We've now narrowed the search to just 3 hash, we can now brute force. For simplicity, the hash that I want is the second one 45e4d5e, and I can recover it by applying it:

git stash apply 45e4d5eRecovering the stash

We've now recovered the stash. It's important to remember that this method works for any unreachable commits, this can happen in a variety of ways:

  • Losing a stash.
  • Deleting a branch.
  • Resetting head to a previous commit.

You can also do a couple more things with the recovered hash:

  • Create a branch: git branch lost-stash 45e4d5e
  • Cherry-pick to another branch: git cherry-pick 45e4d5e
OUR COMPANY
Ippon Technologies is an international consulting firm that specializes in Agile Development, Big Data and DevOps / Cloud. Our 400+ highly skilled consultants are located in the US, France, Australia and Russia. Ippon technologies has a $42 million revenue.