Skip to content

Instantly share code, notes, and snippets.

@davidwalter0
Created August 10, 2017 17:42
Show Gist options
  • Save davidwalter0/401a6ed144a7cb8c04aac716c9454c9c to your computer and use it in GitHub Desktop.
Save davidwalter0/401a6ed144a7cb8c04aac716c9454c9c 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.
@littlerobinson
Copy link

Thanks for this trick !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment