find & restore deleted file in git

How to Find & Restore Deleted File in Git Repository

Git is a popular distributed version control system used by many developers and organizations. Sometimes you may delete a file from your git repository and then commit the change. Then you may work some more commits into your repository. Then you may realize that you want to restore the file you deleted earlier. How do we do this? In this article, we will learn how to find & restore deleted file in Git repository.


How to Find & Restore Deleted File in Git Repository

Here are the steps to find & restore deleted file in git repository.

1. Find Deleted File in Git Repository

Open terminal or command prompt and run the following command to first find the specific commit that deleted the file. Replace <file_path> with the path to your deleted file.

$ git rev-list -n 1 HEAD -- <file_path>

The above command will display the commit ID where your file was deleted.

2. Checkout Deleted File

Next, run the following command to checkout the deleted file. Replace <deleting_commit> with the commit ID which we got in the previous step. Replace <file_path> with the path of deleted file.

$ git checkout <deleting_commit>^ -- <file_path>

You can combine both the above commands into a single command as shown below.

$ git checkout $(git rev-list -n 1 HEAD -- "$file")^ -- <file_path>

If you you use zsh shell then the caret symbol may not work for you. In such cases, replace it with ~1 instead.

$ git checkout $(git rev-list -n 1 HEAD -- "$file")~1 -- <file_path>

If you want a list of all commits that have deleted files, along with the files deleted then run the following command.

$ git log --diff-filter=D --summary

Once you find the required commit, use its commit ID in the above steps to restore the deleted file.

3. Restore Deleted but Not Committed File

The above steps show you how to restore files that have been deleted and the changes have been committed. But if you want to restore file that have been deleted but not committed, you can use the following command.

$ git checkout HEAD -- <file_path>

In this article, we have learnt how to find and restore deleted files in Git repository.

Also read:

How to Set Vim Default Editor in Git
How to Use Variable As Key in JS Object
How to Format Number as Currency String
How to Access iFrame Content With JavaScript
How to Convert Form Data to JSON in JavaScript

Leave a Reply

Your email address will not be published.