How to Recover a Deleted File From a Git Repository

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.

Recent Articles

What is the deal with the Git Index? What is the Git Index?

The git "index" is where you place files you want committed to the git repository. Learn more about the git index and git commit by selecting this link.

Visualising Branches And Their Commits | Git Show-branch

We explain and discuss the use of the git show-branch, gitg, gitk and qgit in this Tutorial. Complete with examples.

“Tracking Branches” And “Remote-Tracking Branches”

Both Tracking Branches and Remote Tracking Branches are created on the git client when a git clone command is used.

Temporarily Stashing Your Work

Git Stash is used when you want to record the current state of the working directory and index, without committing, to come back to complete later.

Shared Repositories Should Be Bare Repositories

Bare Repositories - When creating a central repository that will be shared by other users, the repositories should be created with the --bare option.

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Stay on op - Ge the daily news in your inbox