How To Restore A Deleted File In Git?

Tim Mouskhelichvili
Tim Mouskhelichvili
2 minutes to read

Sometimes after deleting a file, a developer may want to restore it. This task is simple and easy to accomplish if you have already committed the file to the Git repository.

This article will go through different scenarios for a deleted file in Git and explain how to restore it for each.

Let's get to it 😎.

git restore deleted file

Let's say you create a file called index.js.

Then you delete it.

Then you change your mind and want to restore it 😤.

Here is how to recover it for different scenarios.

In this case, the file is located at the project's root. If this isn't the case for you, you need to specify its path to restore it.

How to restore a deleted file before a commit?

To restore a deleted file that you didn't commit, use the git checkout command with the file name, like so:

bashgit checkout HEAD index.js

Note: HEAD refers to the last commit of the active branch.

How to restore a deleted file after a commit?

To restore a deleted file after a commit, you can revert to the previous commit and get the file. However, this approach has a disadvantage because it deletes the other changes you may have made in that commit.

A better approach is to use the git checkout command once again, but specify the previous commit, like so:

bashgit checkout HEAD~1 index.js

This will restore the deleted file from the previous commit.

Note: HEAD~1 refers to the previous commit of the active branch.

How to restore a deleted file after many commits?

If you have made many commits from where you deleted the file to now, you need to find the commit's hash where the file was deleted and checkout to that commit's file.

Here is the process to follow:

1. Find the commit's hash where the file was deleted using the git log command.

bashgit log -- index.js

This lists all the commits containing that file. Usually, what we need is the first commit from the top.

2. Use the git checkout command to restore the file, like so:

bashgit checkout HASH index.js

Read more: Revert multiple commits in Git

How to restore a file after a push?

To restore a file after a push, you can again use the git checkout command with the last commit's hash containing the file, like so:

bashgit checkout HASH index.js

After, you can create a new commit and push your changes.

Bonus: How to restore a file after a merge?

To restore a deleted file after a merge, use the git checkout command, like so:

bashgit checkout HEAD -- index.js

Final thoughts

As you can see, restoring a deleted file in Git is easy.

In most cases, use the git checkout command with the commit's hash containing the deleted file.

git restore deleted file

Here are some other Git tutorials for you to enjoy:

Comments (0)
Reply to: