This blog will explain the procedure of restoring a file from an old commit in Git.
How to Restore File From Old Commit in Git?
To restore the file from an old commit in Git, try out the provided steps:
- Navigate to the local repository.
- List repository content.
- View commit history.
- Choose the desired commit id.
- Restore the file by running the “git restore –source=<commit-id> <file-name>” command.
- Track and commit a file.
Step 1: Redirect to Local Repository
First, type out the below-stated command and switch to the particular local repository:
Step 2: View Repository Content
Then, list the available content of the current repository:
It can be observed that the working repository contains two files:
Step 3: Check Git Status
Next, view the current status of the working directory using the below-provided command:
Step 4: View Commit History
Now, check the Git log to view the commit history:
In the below output, the commits history can be seen. Choose the desired commit whose file needs to be restored. For instance, we have selected the “ec44d52” commit id to restore the “T1.txt” file:
Step 5: Restore Particular File
To restore the specific file from the old commit, run the following command along with the desired commit id and file name:
Step 6: View Repository Status
Now, again check the repository’s current status:
As you can see, the file “T1.txt” file has been restored, but it is untracked and uncommitted:
Step 7: Add File to Git Index
Then, add the untracked file to the Git staging area for tracking purposes:
Step 8: Commit File
Next, use the following command to commit the desired file:
Step 9: Verify Changes
Ensure that desired file has been restored or not by viewing the repository’s content:
It can be observed that now the repository is containing three files and “T1.txt” has been restored from the old commit successfully:
We have efficiently explained the method of restoring a file from old commits in Git.
Conclusion
To restore a particular file from an old commit that no longer exists in the project directory, first, navigate to the local repository. Then, view the repository’s commit history and select the desired commit id that needs to be restored. Next, run the “git restore –source=<commit-id> <file-name>” command to restore the file. After that, stage and commit the file and verify changes. This blog explained the method to restore a specific file from an old commit in Git.