How to Find a Deleted File in a Project's Commit History in Git

John Wachira Feb 02, 2024
How to Find a Deleted File in a Project's Commit History in Git

This article discusses finding a deleted file in a project’s commit history. This is handy when you want to restore a file you deleted in your project.

Without further ado, let’s jump right in.

Steps to Find and Restore a Deleted File in Git

In a scenario where we delete a file and cannot recall the file path, we can execute the below command to find the path.

$ git log --all --full-history -- "<OurFile>"

The command above will output all commits from our commit history containing the files whose names match our pattern <OurFile>. Of course, you will have to substitute <OurFile> with your file’s correct name.

The output can help us get the file path using the commit hashes, as shown below.

$ git show --pretty="" --name-only <sha1-commit-hash>

Now we have the path to our file. However, we want to restore a specific version of the file.

How do we go about this?

As shown below, we will have to get the commits in which the file was changed.

$ git log --all --full-history -- <path-to-file>

To get the version we want, we will run:

$ git show <sha1-commit-hash> -- <path-to-file>

Restore File Into a Working Copy

As illustrated below, we will use the git checkout command to restore our file.

$ git checkout <sha1-commit-hash>^ -- <path-to-file>

We have added the caret symbol ^ to instruct Git to fetch the file version from the previous commit. This ensures we get the previous contents of the file if it was deleted.

In a nutshell, the Git version control system is very strict about losing user data. If there is a file you deleted in your project and you need to restore it, follow the steps we have outlined above.

You do not need to know the full path to the file.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - Git History