乐闻世界logo
搜索文章和话题

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

1个答案

1

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:

bash
git 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:

bash
git 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:

bash
git 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:

bash
git 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:

bash
git log --all --full-history -- **/project-details.md

to find the commit ID (e.g., a1b2c3d4). Then, I view the file's content:

bash
git show a1b2c3d4:project-details.md

Confirming this is the correct file, I execute:

bash
git 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.

2024年8月15日 02:11 回复

你的答案