Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Recover from `git reset --hard` before any initial commit has been made
#!/bin/bash
# This script helps to restore important files after someone acidentially
# ran `git reset --hard` before any commit have been made. `git reflog`
# can´t help you in such cases, because it needs at least one commit
# You can only restore files via this approach, if the files have been
# added with `git add` before the reset was executed! If that was not the
# case, then I have bad news for you: This won´t work :(
# To restore the files, perfom following steps
# 1. Go into the (probably empty) git dir and run `git fsck --lost-found`
# 2. Create a new empty recovery directory
# 3. Place this script somewhere and change the two paths below to match your setup
# 4. Run this script `./recover-lost-git-files.sh`
# This creates a flat directory of files named 0.m - x.m. You can now search this
# directory for textual content and restore your files step by step. Unfortunately
# I don´t know a way, how to restore the original file structure.
# Good Luck!
GIT_DIR=/absolute/path/to/git-dir
RECOVER_DIR=/absolute/path/to/recovery-dir
cd $GIT_DIR/.git/lost-found/other
FILES=*
COUNTER=0
for f in $FILES; do
echo "Processing $f file..."
git show $f > "$RECOVER_DIR/$COUNTER.m"
let COUNTER=COUNTER+1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment