Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recover the index after a git stash / git stash pop?

Tags:

git

git-stash

After adding some changes to the index with git add -p, I then issued a git stash but forgot to add --keep-index. Then I stupidly did a git stash pop, and all my changes to the index were gone. Is there a way to recover the index to the state before the git stash?

like image 619
Watcom Avatar asked Jan 10 '13 18:01

Watcom


People also ask

How do I recover stashed changes in git?

To retrieve changes out of the stash and apply them to the current branch you're on, you have two options: git stash apply STASH-NAME applies the changes and leaves a copy in the stash. git stash pop STASH-NAME applies the changes and removes the files from the stash.

Can I recover a dropped stash git?

Git Stashing Recover a dropped stashYou 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. Or you can use the context menu in gitk to create branches for any unreachable commits you are interested in.

Does git stash pop delete stash?

The key difference between git stash pop and apply involves the stash history. When a developer uses the git stash apply command, the most recently saved stash overwrites files in the current working tree but leaves the stash history alone. In contrast, the pop command restores files but then deletes the applied stash.


2 Answers

When you've just done git stash pop, the last line in the output is:

Dropped refs/stash@{0} (ca82a6dff817ec66f44342007202690a93763949)

If you've lost it, see How to recover a dropped stash in Git? to find the commit hash.

Once you have the hash, either:

  • Drop all current changes (applied stash):

    git reset --hard

    And reapply the stash using its id, this time with index:

    git stash apply ca82a6d --index

  • Reset only the index, the point here is that the index is saved as a second parent of the stash:

    git reset ca82a6d^2 .

    Notice the dot at the end. If you don't specify it, it'll also move HEAD to the index (the index will appear as a commit). In this case run git reset --soft HEAD@{1} to return the HEAD to its previous position.

like image 95
user Avatar answered Oct 24 '22 11:10

user


This will do the job:

git stash apply --index

Edit: Considering the index is already lost, you should run a git fsck --unreachable and inspect the latest commits it gives. You must be able to see your lost index there. After that you can git cherry-pick it.

like image 37
maliayas Avatar answered Oct 24 '22 11:10

maliayas