How Do I Find and Restore a Deleted File in a Git Repository?

Better Stack Team
Updated on June 24, 2024

To find and restore a deleted file in a Git repository, you can follow these steps:

Step 1: Use git log to Find the Commit Where the File Was Deleted

 
git log -- <deleted-file-path>

Replace <deleted-file-path> with the path to the deleted file. This command will display the commit history for the file, including the commit where it was deleted.

Step 2: Check Out the Commit Before the File Was Deleted

Identify the commit just before the file was deleted. You can use the commit hash or any reference (e.g., branch name) to checkout that commit.

 
git checkout <commit-hash>

Replace <commit-hash> with the hash of the commit just before the file was deleted.

Step 3: Copy the Deleted File from the Checked Out Commit

After checking out the previous commit, you can copy the deleted file from that commit to your working directory:

 
git show <commit-hash>:<deleted-file-path> > <restored-file-path>

Replace <commit-hash> with the commit hash you checked out, <deleted-file-path> with the path to the deleted file within that commit, and <restored-file-path> with the desired path for the restored file in your working directory.

Step 4: Add and Commit the Restored File

After restoring the deleted file to your working directory, you need to add and commit it to the repository:

 
git add <restored-file-path>
git commit -m "Restored <deleted-file-path>"

Replace <restored-file-path> with the path to the restored file.

Note:

  • If you're unsure about the commit where the file was deleted, you can use git log -- <deleted-file-path> to review the commit history and identify the appropriate commit.
  • Be cautious when restoring deleted files, as they might have been intentionally removed. Make sure to consult with other collaborators or review the commit history before restoring.
  • After restoring the file, you should review its contents to ensure it's restored correctly and doesn't conflict with any changes made after its deletion.
Got an article suggestion? Let us know
Explore more
Git
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.