Skip to content

Instantly share code, notes, and snippets.

@tomraithel
Created August 10, 2018 20:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomraithel/2faa400b4d83b4cdcb303ee13177f59c to your computer and use it in GitHub Desktop.
Save tomraithel/2faa400b4d83b4cdcb303ee13177f59c to your computer and use it in GitHub Desktop.
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