how to recover a dropped stash in git

Sometimes, you use git stash to save some changes. Then, you git stash pop them, which puts them back in your working copy and then gets rid of them.

Say you want to look at a stash, or maybe re-apply that stash later. They were saved at some point, how do you get them back?

A stash is just a commit, just saved in a different place, and we don't just have a reference to it anymore. If we know the commit name, then we can bring it back in a number of ways.

Here are some ways that I've found to get these back:

Look at the output of where you popped it

        $ git stash pop
        # On branch master

        ....
        Dropped refs/stash@{0} (3d611c6eabbb91456cd2fbfd5f89bc24d4ae03ab)
        

Once you know the ref, use git branch temp 3d611 to make it into a branch, then you can review, merge, or cherry-pick it.

Get a list of 'dangling commits' and show them in a viewer

Try this: git fsck --unreachable

You'll see messages like 'dangling tree' and 'dangling commit' and 'dangling blog' in the output. Those are objects that are "present in the database but never directly used" (from the manpage.) Essentially, objects that are used nowhere in the history.

Then, you can use the graphical git viewer to see all the stash names and pick the one you want: gitk --all $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' )

Finally, save that commit SHA as a branch with git branch temp SHA and then manipulate it from there.

List them in the shell

This is essentially the same idea, but runs through each ref and shows the summary in the shell.

for ref in `git fsck --unreachable | grep commit | cut -d' ' -f3`; do git show --summary $ref; done | less

Avoid this in the first place!

Finally, if you use git stash apply then it doesn't remove the stash, so you can do something else with it later without going through all these steps. git stash drop and git stash clear will get rid of one / all of the stashes if you need, as well.

Established 2005 · Databasically © 2016