Retrieve a lost stash!

Posted: November 1, 2018 Category: backendTagged: gitcode snippets

Have you been too git stash happy and then ended up with a whole bunch and then got confused? Or worse, lost a stash?

Do this on cmd line or git bash window:

git fsck --no-reflog | awk '/dangling commit/ {print $3}' | xargs -L 1 git --no-pager show -s --format="%ci %H" | sort

It lists all the dangling commits hiding somewhere, by the SHA # of each such commit. To see which hash you might be after if you can’t remember contents of each one, just do: git diff <SHA> using the sha of the commit.

Note: The diff might be backwards (left & right swapped, so read the diff qualitatively). Once you know which hash looks like the contents you want, don’t just stash pop… that will destroy the commit, and if you picked the wrong, one, it’s pretty much gone forever. So instead, do git stash apply <SHA>.

ta-da!! Hope that helps someone out there. And my future self, because I WILL NOT REMEMBER HOW TO DO THIS otherwise… (I also prolly won’t remember to look here when I run into this again, lol!).