When you need to find and restore deleted files in a Git repository, follow these steps:
1. Locate the Last Commit That Deleted the File
First, identify the commit that removed the file. You can use the git log command with specific parameters to locate the relevant commit. Here's a practical command:
bashgit log --all --full-history -- <file_path>
Here, <file_path> refers to the path of the file you want to recover. If you're unsure about the exact path, you can:
bashgit log --all --full-history -- **/<filename>
This command helps you find all records matching the filename.
2. View the File's Content
Once you've identified the relevant commit, view the file's content using:
bashgit show <commit_id>:<file_path>
Here, <commit_id> is the ID of the commit found in the previous step, and <file_path> is the file's path at that commit.
3. Restore the File
If you confirm this is the file you want to restore, use:
bashgit checkout <commit_id> -- <file_path>
This command restores the file from the specific commit without altering other files.
Example
Suppose I accidentally deleted project-details.md and committed the change. To restore it, I first run:
bashgit log --all --full-history -- **/project-details.md
to find the commit ID (e.g., a1b2c3d4). Then, I view the file's content:
bashgit show a1b2c3d4:project-details.md
Confirming this is the correct file, I execute:
bashgit checkout a1b2c3d4 -- project-details.md
This restores project-details.md to my working directory while leaving other files unchanged.
By following these steps, you can effectively recover deleted files even after they've been committed and modified.