Recover When Git Stashes Mistakenly Deleted

Recover When Git Stashes Mistakenly Deleted

Takahiro Iwasa
Takahiro Iwasa
2 min read
Git

Even if you accidentally delete git stashes, you can still recover the files from the stashes.

Outputting Commit History

Output commit history with the following command.

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

You will see the result like the following.

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

Outputting Commit Summary

Run the following command to output commit summary.

#!/bin/bash

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

You will see the result like the following.

commit bfebf68feeebf07a86d7e3e4da77962de67c14ee
Merge: b046240 5ee731a
Author: Takahiro Iwasa <[email protected]>
Date:   Fri Feb 12 22:01:47 2016 +0900

    On develop: 0212

Identifying Commit Ids Which You Want to Restore

Based on the date and time, commit message, and other factors, identify the commit IDs that you want to restore from the above output.

Restoring

Run the following command to cherry pick commits with the commit ID.

git cherry-pick -n -m1 <YOUR_COMMIT_ID>

Conclusion

If you have deleted your stashes mistakenly, please keep calm and do the process above, so you will be able to recover them.

I hope you will find this post useful.

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.