Git Undo Reset Hard: Recover Staged Files Which Got Deleted By Git Reset –Hard (Linux)

Did you ever delete hours of progress by carelessly using git reset --hard? I did, so I spent the next hours searching for a way to restore my hard work which I will share with you here. This solution only works for files which got staged before the reset (e.g. by git add *) and are still cached by git. The full script is free for download.

The first step of the solution is to find the deleted files. I based my approach on Mark Longair’s stackoverflow answer using the version which sorts by timestamp (suggested by Philip Oakley). So after navigating into the repository we search for all unreachable files, sort them by timestamp and write the hashes to a file.

find .git/objects/ -type f -printf '%TY-%Tm-%Td %TT %p\n' | sort | cut -d " " -f 3 | sed "s/\.git\/objects\/\(.*\)\/\(.*\)/\\1\\2/" > file_hashes_to_recover.txt

As next step we compile git recovery commands with these hashes which we write to another file.

awk '{FS="\t"} {print "git show "$1" > recovered"FNR}' file_hashes_to_recover.txt > file_recovery_commands.txt

Finally we run the git recovery commands restoring all unreferenced cached files.

bash file_recovery_commands.txt

In ended up with a few hundred files as shown below where the first ~30 contained all relevant files I needed to restore.

As a last step you need to manually go through the files, take a look at them as well as rename or copy the relevant ones. This step can be simplified by adding the correct file endings as described in this post here.


One comment

  1. […] files I sometimes face the problem of lost file names and file extensions (most recent case here). To help me dealing with this I problem I need a way to automatically add the file extension, […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: