Skip to content

Instantly share code, notes, and snippets.

@raevilman
Forked from davidwalter0/stash-pop-recover
Created June 21, 2021 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raevilman/b912b8cdfb7ae13bdbe622804491f809 to your computer and use it in GitHub Desktop.
Save raevilman/b912b8cdfb7ae13bdbe622804491f809 to your computer and use it in GitHub Desktop.
Undoing accidental git stash pop
# https://stackoverflow.com/questions/6543519/undoing-accidental-git-stash-pop
# https://stackoverflow.com/questions/89332/how-to-recover-a-dropped-stash-in-git
accepted
If you have only just popped it and the terminal is still open, you will still have the hash value printed by git stash pop on screen (thanks, Dolda).
Otherwise, you can find it using this for Linux and Unix:
git fsck --no-reflog | awk '/dangling commit/ {print $3}'
and for Windows:
git fsck --no-reflog | select-string 'dangling commit' | foreach { $bits = $_ -split ' '; echo $bits[2];}
This will show you all the commits at the tips of your commit graph which are no longer referenced from any branch or tag – every lost commit, including every stash commit you’ve ever created, will be somewhere in that graph.
The easiest way to find the stash commit you want is probably to pass that list to gitk:
gitk --all $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' )
This will launch a repository browser showing you every single commit in the repository ever, regardless of whether it is reachable or not.
You can replace gitk there with something like git log --graph --oneline --decorate if you prefer a nice graph on the console over a separate GUI app.
To spot stash commits, look for commit messages of this form:
WIP on somebranch: commithash Some old commit message
Note: The commit message will only be in this form (starting with "WIP on") if you did not supply a message when you did git stash.
Once you know the hash of the commit you want, you can apply it as a stash:
git stash apply $stash_hash
Or you can use the context menu in gitk to create branches for any unreachable commits you are interested in. After that, you can do whatever you want with them with all the normal tools. When you’re done, just blow those branches away again.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment