How to recover a dropped stash in Git?

前端 未结 19 1734
别跟我提以往
别跟我提以往 2020-11-22 01:42

I frequently use git stash and git stash pop to save and restore changes in my working tree. Yesterday I had some changes in my working tree that I

相关标签:
19条回答
  • 2020-11-22 01:51

    My favorite is this one-liner:

    git log --oneline  $( git fsck --no-reflogs | awk '/dangling commit/ {print $3}' )
    

    This is basically the same idea as this answer but much shorter. Of course, you can still add --graph to get a tree-like display.

    When you have found the commit in the list, apply with

    git stash apply THE_COMMIT_HASH_FOUND
    

    For me, using --no-reflogs did reveal the lost stash entry, but --unreachable (as found in many other answers) did not.

    Run it on git bash when you are under Windows.

    Credits: The details of the above commands are taken from https://gist.github.com/joseluisq/7f0f1402f05c45bac10814a9e38f81bf

    0 讨论(0)
  • 2020-11-22 01:53

    You can achieve this in 2 easy steps

    1. List lost stashes --> run this command for a project where all stashes were trashed:

      git fsck --unreachable | grep commit | cut -d ' ' -f3 | xargs git log --merges --no-walk

    2. Send a lost stash back where it comes from --> Let’s use the commit hash of the second stash:

      git update-ref refs/stash 4b3fc45c94caadcc87d783064624585c194f4be8 -m "My recovered stash"

    0 讨论(0)
  • 2020-11-22 01:55

    You can list all unreachable commits by writing this command in terminal -

    git fsck --unreachable
    

    Check unreachable commit hash -

    git show hash
    

    Finally apply if you find the stashed item -

    git stash apply hash
    
    0 讨论(0)
  • 2020-11-22 01:56

    Just wanted to mention this addition to the accepted solution. It wasn't immediately obvious to me the first time I tried this method (maybe it should have been), but to apply the stash from the hash value, just use "git stash apply ":

    $ git stash apply ad38abbf76e26c803b27a6079348192d32f52219
    

    When I was new to git, this wasn't clear to me, and I was trying different combinations of "git show", "git apply", "patch", etc.

    0 讨论(0)
  • 2020-11-22 02:00

    I want to add to the accepted solution another good way to go through all the changes, when you either don't have gitk available or no X for output.

    git fsck --no-reflog | awk '/dangling commit/ {print $3}' > tmp_commits
    
    for h in `cat tmp_commits`; do git show $h | less; done
    

    Then you get all the diffs for those hashes displayed one after another. Press 'q' to get to the next diff.

    0 讨论(0)
  • 2020-11-22 02:02

    git fsck --unreachable | grep commit should show the sha1, although the list it returns might be quite large. git show <sha1> will show if it is the commit you want.

    git cherry-pick -m 1 <sha1> will merge the commit onto the current branch.

    0 讨论(0)
提交回复
热议问题