How to Recover Deleted Git Stashes

How to Recover Deleted Git Stashes

Takahiro Iwasa
Takahiro Iwasa
2 min read
Git

Introduction

Accidentally deleting Git stashes can be a frustrating experience. Fortunately, there are ways to recover them. This guide walks you through the steps to identify and restore deleted stashes in Git.

Step 1: Output Commit History

Use the following command to output commit history and identify dangling commits:

git fsck | awk '/dangling commit/ {print $3}' >> commit_list.txt

The output will look something like this:

dangling commit bfebf68feeebf07a86d7e3e4da77962de67c14ee
dangling commit 86f4aec78bd51c80b0fd2d5d83963a2259dc72b4
dangling commit 48fd9f8f97a577bc8a87b133f6e1dd789a692bd0
dangling commit 64ff8c33fb878afb8bf5c99c1b8d8fdfaa1b1f3c
dangling commit bdff88e13803e6c7737691aa1fb6f1e038321966

Step 2: Output Commit Summaries

To review commit details, run the following script:

#!/bin/bash

while read line
do
  git show $line
done < ./commit_list.txt

This will display summaries of the dangling commits:

commit bfebf68feeebf07a86d7e3e4da77962de67c14ee
Merge: b046240 5ee731a
Author: Takahiro Iwasa <iwasa.takahiro@wasabee.io>
Date:   Fri Feb 12 22:01:47 2016 +0900

    On develop: 0212

Step 3: Identify Commits to Restore

Carefully review the commit summaries and use the date, time, and commit message to identify the commits you wish to restore.

Step 4: Restore Selected Commits

Restore the identified commits using git cherry-pick. Use the following command:

git cherry-pick -n -m1 <YOUR_COMMIT_ID>

Replace <YOUR_COMMIT_ID> with the commit ID of the stash you want to recover.

Conclusion

By following these steps, you can effectively recover deleted Git stashes. Remember to stay calm and methodical in your recovery process.

Happy Coding! 🚀

Takahiro Iwasa

Takahiro Iwasa

Software Developer at KAKEHASHI Inc.
Involved in the requirements definition, design, and development of cloud-native applications using AWS. Now, building a new prescription data collection platform at KAKEHASHI Inc. Japan AWS Top Engineers 2020-2023.