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
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
You can achieve this in 2 easy steps
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
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"
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
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.
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.
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.