Recover When Git Stashes Mistakenly Deleted

Recover When Git Stashes Mistakenly Deleted

Takahiro Iwasa
(岩佐 孝浩)
Takahiro Iwasa (岩佐 孝浩)
1 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>
Takahiro Iwasa
(岩佐 孝浩)

Takahiro Iwasa (岩佐 孝浩)

Software Developer at iret, Inc.
Architecting and developing cloud native applications mainly with AWS. Japan AWS Top Engineers 2020-2023