How to Recover a Deleted File From a Git Repository

In: Repositories

7 Dec 2012

Git Repository Deleted File Recovery Method

Sometimes you want to recover a file you deleted from a git repository.
Sometimes you want to recover a file somebody else deleted from a git repository.

Recovering a deleted file from the git repository, after a commit, is not complicated if you know the right commands and method for doing so. This quick tutorial walks you this the recovery processes. The process takes 3 steps:

  1. Find all of the files deleted from the repository
  2. Find information about the specific file we are interested in
  3. Restore the file!

That is all there is to it. Let’s get started.

List all files that have been deleted from a git repository:

git log --diff-filter=D --summary | grep delete

If you know the exact filename of the deleted file you can skip this step.

List information about a particular filename that has been deleted from a git repository:

git log -- [deleted-filename]

Restore a file that has been deleted from a git repository:

Next you are ready to find the last commit before the file was deleted:

git rev-list -n 1 HEAD -- [deleted-filename]

Now that you have the last commit, check out the repository at the commit BEFORE the file was deleted:

git checkout ~1 -- [deleted-filename]

That is it. Your deleted file has been recovered.

Avatar

Tajju

December 19th, 2012 at 3:54 am

You can also put the name of the folder to be igorned into the exclude’ file in .git/info’.That way, you have all your ignores in one central place and don’t have to commit that change.

Avatar

Bill

August 23rd, 2013 at 7:15 pm

For “git checkout ~1 — [deleted-filename]“, it should be “git checkout delete_commit^ [deleted-filename]”

Here “delete_commit” is the result of “git rev-list -n 1 HEAD — [deleted-filename]”

Am I right?

Cheers! Happy to read your post!

Avatar

Ville

October 31st, 2013 at 1:16 pm

You probably also need to add quotes around the commit hash, like so:

git checkout “delete_commit^” path/to/deleted_filename

At least I could not get it to work with “parent” specifier (^) without the quotes. A plain commit hash doesn’t seem to require quotes.

Comment Form