If you've deleted files in a Git repository and want to restore them, the method depends on how the files were deleted. Here's a step-by-step guide to recover them:
1. If the files were deleted using git rm (tracked files)
Git tracks these deletions, so you can easily restore them.
Option A: Use git checkout to restore files from the last commit
git checkout <commit-hash> -- <file-path>
Option B: Use git restore (Git 2.23+)
git restore <file-path>
2. If the files were deleted without Git (e.g., using rm or a file manager)
Git doesn't track untracked files, so recovery depends on whether the files were committed or untracked.
A. If the files were committed and then deleted:
B. If the files were untracked (not committed):
- No direct Git recovery is possible unless:
- You have a backup of the files.
- You used a file system backup (e.g., Time Machine, cloud storage).
- You check the reflog for recent commits that might include the files.
C. Use git fsck to find lost commits (advanced)
If the files were committed and then deleted, run:
git fsck --lost-found
This lists "dangling" commits. Find the commit that contains your files and check it out:
git checkout <dangling-commit-hash>
3. If you accidentally deleted files and haven't committed the deletion
-
Undo the deletion using git reset:
git reset --hard
This reverts all changes (including deletions) in the working directory to the last commit.
-
Restore specific files:
git checkout -- <file-path>
4. If the files were deleted from a remote repository
5. If All Else Fails
-
Check the reflog for recent actions:
git reflog
Look for a commit that includes the deleted files and check it out.
-
Use third-party tools (e.g., extundelete, testdisk) to recover files from the file system if they were deleted without Git tracking.
Summary Table
| Scenario | Command |
|---|
Deleted via git rm | git checkout HEAD -- <file> |
| Untracked files deleted | No Git recovery; use backups. |
| Accidentally deleted (uncommitted) | git checkout -- <file> |
Lost commits (via git fsck) | git fsck --lost-found |
| Remote deletion | git fetch origin && git reset --hard |
Let me know if you need further clarification! 🚀