How do I find and restore a deleted file in a Git repository?

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

1. Find the Commit Where the File Was Deleted

Use git log to search for the commit that deleted the file:

git log --diff-filter=D -- <file-path>

Example:

git log --diff-filter=D -- src/app.js

This shows the commit hash (e.g., abc123) where the file was deleted.

2. Restore the File from the Last Known Commit

If you know the file existed in a previous commit, restore it using:

# From the commit before deletion
git checkout <commit-hash>^ -- <file-path>

Example:

git checkout abc123^ -- src/app.js

This checks out the file from the commit just before the deletion.

3. Restore from a Specific Commit

If you know the exact commit where the file existed:

git checkout <commit-hash> -- <file-path>

Example:

git checkout def456 -- src/app.js

4. Use git restore (Git 2.23+)

Restore the file from the last commit where it existed:

git restore --source=HEAD~1 -- <file-path>

Example:

git restore --source=HEAD~1 -- src/app.js

5. Recover from the Git Reflog

If you don’t know the commit hash, use git reflog to find the state of the repo before the deletion:

git reflog
# Identify the commit where the file existed (e.g., HEAD@{3})
git checkout HEAD@{3} -- <file-path>

6. Restore a Deleted File in a New Branch

Create a new branch to recover the file without affecting your current work:

git checkout -b recovery-branch
git checkout <commit-hash> -- <file-path>
git add <file-path>
git commit -m "Restore deleted file"

7. Restore All Deleted Files

To restore all deleted files from the last commit:

git ls-files --deleted | xargs git checkout --

Key Notes

  • If the file was never committed, it cannot be restored from Git history.
  • Use git gc with caution—it prunes unreachable commits, which may permanently delete unreferenced files.

Example Workflow

  1. Find the deletion commit:
   git log --diff-filter=D -- src/utils.js

Output:

   commit abc123 (HEAD -> main)
   Author: John Doe <john@example.com>
   Date:   Mon Jan 1 12:00:00 2023
       Delete src/utils.js
  1. Restore the file from the commit before deletion:
   git checkout abc123^ -- src/utils.js
  1. Commit the restored file:
   git add src/utils.js
   git commit -m "Restore src/utils.js"

Advanced: Recover from Dangling Blobs

If the file isn’t in any commit history, search for dangling blobs (orphaned file versions):

git fsck --lost-found

Check the .git/lost-found/other/ directory for recoverable files.

Leave a Reply

Your email address will not be published. Required fields are marked *