Recovering Lost Files in a Git Repository: A Step-by-Step Guide

Have you ever accidentally deleted a file from your Git repository and later realised it was crucial? Losing a file like your-missed-filename.html can be frustrating, especially when you don’t remember which branch it was in. In this blog post, I’ll walk you through the steps to recover a missing file across different branches in your Git repository.

Scenario

You’re working on a project hosted on GitHub, and you mistakenly delete a file called your-missed-filename.html. Now, you’re unsure which branch had the file. Don’t worry! With Git, you can search through your branches to find and recover the file.

Step 1: Clone the Repository

If you don’t already have the repository cloned on your local machine, start by cloning it:



git clone https://github.com/lalatenduswain/git-reponame.git

cd git-reponame


This will create a local copy of the repository on your machine.

Step 2: Fetch All Branches

To make sure you have the latest changes and all branches from the remote repository, run:



git fetch --all


This command fetches all branches and updates your local copy with any new commits from the remote repository.

Step 3: Search for the File Across All Branches

Now that you have all branches locally, it’s time to search for the your-missed-filename.html file across all branches.

Search Using git log and grep:
This method searches the Git history to find where the file was added or modified:

git log --all --name-only --pretty=format: | grep "your-missed-filename.html"

Find the Branch Containing the File:
After identifying the commit that contains the file, use the commit hash to find the branch:

git branch -a --contains <commit-hash>

Alternative Method Using git grep:
If you want to search through all branches more efficiently, use git grep:

git grep "your-missed-filename.html" $(git rev-list --all)

Step 4: Recover the File

Once you’ve identified the branch that contains the file, you can switch to that branch and recover the file.

Checkout the Branch:

git checkout branch-name

Replace branch-name with the name of the branch where the file exists.

Copy the File:
If you want to bring the file back to your current branch, simply copy it:

cp path/to/your-missed-filename.html /path/to/current/branch

Or, if you want to restore it directly in the current branch, use Git to checkout the file:

git checkout branch-name -- path/to/your-missed-filename.html

Conclusion

Losing files in Git might seem daunting, but with the right commands, you can quickly recover them. Whether it's searching through commit history or checking branches, Git provides powerful tools to help you track down and restore your lost work. By following this guide, you’ll be able to confidently recover your your-missed-filename.html file—or any other lost file—across your Git repository.