Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can deleted files that are added but not committed in Git be recovered? [duplicate]

Tags:

git

recover

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.

like image 514
user1672893 Avatar asked Sep 15 '12 04:09

user1672893


People also ask

How recover deleted files before commit?

If you have deleted the file and already committed the changes, you need to use the ` git checkout` command to restore the file. First, you need to find out the checksum of the commit that deleted the file, and then check out the file from the previous commit.

What happens to deleted files in git?

Git keeps a log of all the changes made to files within a repository. You can restore a file that you have deleted since a previous commit by using the git checkout command. This command lets you navigate to a previous point in your repository's history.

Does git add/remove deleted files?

To add a single file to the commit that you've deleted, you can do git add what/the/path/to/the/file/used/to/be . This is helpful when you have one or two deletions to add, but doesn't add a batch of deletions in one command.

Can I get back deleted commit git?

The process for recovering a deleted commit is quite simple. All that is necessary is to use `git reflog` to find the SHA value of the commit that you want to go to, and then execute the `git reset --hard <sha value>` command.


2 Answers

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.

like image 68
user4815162342 Avatar answered Sep 20 '22 23:09

user4815162342


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.

like image 30
Lily Ballard Avatar answered Sep 17 '22 23:09

Lily Ballard