Restore deleted Git stash

Last Updated on by

Post summary: How to restore deleted Git stash.

Git

Git is a version control system, which is conceptually different than others. It is a mini file system, which has all the information locally. Git support fully local work, no internet connection is needed once the project is checked out. All changes are done locally and saved to the local database. Once there is internet connection changes can be synced to the server and available for others as well. See more in What is Git? page.

Git stash

Git offers so-called stashing. Current work can be temporarily saved, without being committed. When current work is stashed, the repository is reverted back to the original state. One possible use case is when new conflicting changes from the upstream are coming. Current work has to be saved, remote changes applied and then, the current work to be completed.

Many changes can be stashed. The problem with having several stashes is that there is no easy way to merge the stashes. So it is recommended not to have more than one stash at a time.

Common stash operations

The most important actions that can be done on a stash are:

  • git stash – saves current work to stash
  • git stash list – shows all stashed changes
  • git stash apply – apply the latest stash
  • git stash clear – removes all stashes

More details can be found in git-stash page.

Restore deleted Git stash

It happened several times that I am working on something important with many changes, but then I need to switch to another thing. I do not want to commit the work, as it is messy, so I have to stash it. Then I accidentally deleted the stash. The worst thing that happened was two weeks of work stash to get deleted, quite upsetting.

Luckily Git is a really sophisticated version control system and it saves intermediates states, so stash is not really lost. It can be restored. I have a favorite article on the topic, Recover a dropped Git stash. There are some command line suggestions in it, but what I love is:

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

In the screenshot, it is very clearly shown the stash and the file changes into it. Then those changes can be manually applied.

Conclusion

Git is a very sophisticated version control system, more like a mini file system. It allows you to stash changes that are not ready to be committed yet. Stashes can be accidentally deleted. The good thing is there is a mechanism to restore deleted stashes.

Category: Tutorials | Tags: