Files are the essential part of Git that is utilized to manage the project source code. In Git, all of the changes take place through files. Then, these changes are committed to save in a local repository. However, sometimes developers may accidentally delete the committed file and later want to restore it. If the user does not commit any changes after deleting a file, then they can restore the deleted file to the Git repository.
This blog will demonstrate how to recover deleted files where no commit was made after deletion.
How to Recover Deleted Files Before Committing Changes?
To recover the deleted file before committing new changes, first move to the Git repository. After deleting a file, the user can recover it using the βgit checkout Head <file-name>β command.
Step 1: Open Git Terminal
First, from the Start menu, open the Git terminal:
Step 2: Go to Git Repository
Use the βcdβ command to go to the Git repository:
Step 3: Generate New File
Generate a new file in the Git repository through the βtouchβ command:
After that, check the repository status to verify if the file is generated or not:
Step 4: Move File to Tracking Index
Next, move the untracked file to the tracking area by utilizing the below command:
Step 5: Commit Changes to Repository
Commit the tracked changes through the mentioned command:
Step 6: Remove File
Now, remove the committed file from the Git working repository using the βgit rmβ command:
Verify the file deletion option by listing the content:
You can see that the file is deleted from the repository:
Step 7: Recover Deleted File
After that, recover the deleted file before committing any changes using the βgit checkout Head <file-name>β command:
Here, specify the deleted file name which you want to recover:
Again, utilize the βlsβ command and verify whether the file is recovered or not:
The below output shows that we have successfully recovered the deleted file:
We have taught you the method to recover deleted files where no commit was made after deletion.
Conclusion
To recover the deleted file before committing new changes, first go to the Git local repository, where the file is deleted after the commit, and no new changes are committed yet. To recover the deleted file, utilize the βgit checkout Head <file-name>β command. In this post, we have elaborated on the method to recover the deleted file where no new changes are committed after deletion.