Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recover files that were added to git, not committed and then accidentally deleted by git reset --hard

Tags:

git

I have a huge problem. Yesterday I mistaken development and production terminals opened side-by-side and ran

git add .

on production. That caused staging all files in public/uploads path. When I tried

git status

It showed all files in public/uploads are staged and ready to commit. But I never committed these changes, because on production I don't want any commits or pushes. SSH key on production doesn't have permission to push, only clone/pull.

So I ran these commands to force pull my new code from remote repository

git fetch --all
git reset --hard  origin/master
git pull origin master

But now I find out that it has deleted all files in public/uploads path and the directory it self. When I check

git status

I see "Your branch is up-to-date with 'origin/master' ". Is there a way how to recover files from deleted directory? These files are pretty important...

like image 323
Patrik Šimunič Avatar asked Oct 31 '25 16:10

Patrik Šimunič


1 Answers

As far as I understand, git add registers its argument files in the repository even before they are committed. If they are not committed, then they will be garbage collected later. Therefore there should be a way of restoring the files from the repository if you act promptly.

Try running the following bash script in the root of your repository directory. It will create a new subdirectory recovering_lost_files that will contain git objects that are newer than your HEAD commit (and therefore correspond to git add-ed but uncommitted files). Unfortunately, the names of the files will not be automatically recovered.

recover_lost_files:

#!/usr/bin/env bash

headcommit="$(git log --format=format:%H)"
headcommitobject=".git/objects/${headcommit:0:2}/${headcommit:2}"
mkdir recovering_lost_files
find .git/objects/ -type f -newer "$headcommitobject"|while read -r path
do
    obj="${path#.git/objects/}"
    obj="${obj/\/}"
    git cat-file -p $obj > recovering_lost_files/$obj
done
like image 164
Leon Avatar answered Nov 02 '25 07:11

Leon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!