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

Where Do I Get Git?

Where do you get git? We have the answer to that for Linux (Ubuntu, Debian, and Red Hat), Windows, and Apple OS as well as over 30 free git tutorials.

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.

What Every VCS Must do

Version Control System ("VCS") need to be able to provide to its users? GitGuys explains exactly what it needs to include and provides tutorials on Git.

Visualising Branches And Their Commits

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.

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Stay on op - Ge the daily news in your inbox