How to undo git stash clear
As it may be found in the documentation of git stash, you may be lucky if this works:
Recovering stashes that were cleared/dropped erroneously
If you mistakenly drop or clear stashes, they cannot be recovered through the normal safety mechanisms. However, you can try the following incantation to get a list of stashes that are still in your repository, but not reachable any more:
git fsck --unreachable | grep commit | cut -d\ -f3 | xargs git log --merges --no-walk --grep=WIP
If you find the stash you cleared by mistake, then you can do:
git stash apply <stash>
EDIT: Use this command instead git fsck --unreachable | grep commit | cut -d ' ' -f3 | xargs git log --merges --no-walk --grep=WIP
All of the above answers end with a git stash apply [commit]
which is good, but is not an exact undo of git stash clear
. For that you need to re-stash the orphaned stash-commit. I found these instructions which almost worked but needed a flag to get all the way there. Summarizing:
- Find the orphaned stash commits:
git fsck --unreachable | grep commit | cut -d ' ' -f3 | xargs git log --merges --no-walk
- Re-stash the commit:
git update-ref --create-reflog refs/stash 4b3fc45c94caadcc87d783064624585c194f4be8 -m "My recover stash"
Run this command to find the commit:
git fsck --unreachable | grep commit | cut -d ' ' -f3 | xargs git log --merges --no-walk --grep=WIP
will list something like:
Checking object directories: 100% (256/256), done.
commit c36e565014d9a927c36f16e78bc327eb375d33b8
Merge: dff6bc1 4e05a0c
Author: suhailvs <[email protected]>
Date: Thu Jul 19 13:32:01 2018 +0530
WIP on master: dff6bc1 added menu
then checkout that commit c36e565014
:
git checkout c36e565014
I had to use
git fsck --unreachable | grep commit | cut -d ' ' -f3 | xargs git log --merges --no-walk
to fetch all the orphan stash which will give an o/p similar to this:
Checking object directories: 100% (256/256), done.
Checking objects: 100% (395/395), done.
commit 3928306034b292770cc4cd2987c034ffad250e0b //commit stash hash
Merge: 16056a0 ac3c354
Author: Jimmy <mail>
Date: Thu Nov 14 17:31:05 2019 +0530
On profile: stashing for
commit 50f6f3a7161dd44bfcef2b8328a2329db4c7ec34
and use
git apply stash 3928306034b292770cc4cd2987c034ffad250e0b
And I got my stashed changes back. Thanks to https://mobilejazz.com/blog/how-to-recover-a-deleted-git-stash/