5

I am new to git, and I just made a stupid mistake, that I deleted some important files by "rm *" command. However, I did use "git add" to add those files, but not commit. the deletion is not added yet. So is there any way to recover these deleted files.

Any suggestions or answers would be appreciated. Thanks.

elclanrs
  • 92,861
  • 21
  • 134
  • 171
user1672893
  • 61
  • 1
  • 3

2 Answers2

7

Since the files are already in your staging area (index), simply commit them using git commit without any arguments. This will commit the contents of the index regardless of the current state of the working tree.

Then you can use git reset --hard (if you don't have other changes in the tree you want to keep) or git checkout FILE1 FILE2... to restore the lost files into your working tree.

user4815162342
  • 141,790
  • 18
  • 296
  • 355
6

You can use git fsck --lost-found to find all objects that are no longer referenced. You'll want to look at 'blob' objects and see if any of them match the files you deleted. Hopefully you don't have many unreferenced objects lying around.


As user4815162342 pointed out, the poster actually said the deletion had not been added yet, which means they can be retrieved with git checkout, or simply committed right now to be sure they don't go away.

I'm going to leave my answer up in case anyone else wants info on git fsck --lost-found, but user4815162342's answer should be accepted.

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
  • 1
    Hi, Thanks for the response. I ran the command, and saw a list of dangling blob like this, then how do I get the deleted files back?dangling blob 029530a4ebc7dec791a58cb022e18d0d87c8fe04 dangling blob 0c871fff49c4a05ff4a49b6a910f3bc4b688e338 dangling blob 0c08f1e149bfa9e84e9e30867c931423267b91c7 – user1672893 Sep 15 '12 at 05:11
  • 2
    `git fsck --lost-found` writes all dangling objects into the `.git/lost-found/commit/` or `.git/lost-found/other/` folders. Go look through the `other` folder and try to find the files in there that contain what you deleted. The names will be SHA1 hashes but the contents will be the actual file. – Lily Ballard Sep 15 '12 at 07:19
  • You can also print individual objects via `git cat-file -p SHA1` – Ana Betts Sep 15 '12 at 07:27