Git

How to Recover Deleted File Where no Commit was Made After Deletion

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:

$ cd "C:\Git\Design"

Step 3: Generate New File

Generate a new file in the Git repository through the β€œtouch” command:

$ touch Demo.txt

After that, check the repository status to verify if the file is generated or not:

$ git status

Step 4: Move File to Tracking Index

Next, move the untracked file to the tracking area by utilizing the below command:

$ git add .

Step 5: Commit Changes to Repository

Commit the tracked changes through the mentioned command:

$ git commit -m "New Commit"

Step 6: Remove File

Now, remove the committed file from the Git working repository using the β€œgit rm” command:

$ git rm Demo.txt

Verify the file deletion option by listing the content:

$ ls

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:

$ git checkout Head Demo.txt

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:

$ ls

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.

About the author

Rafia Zafar

I am graduated in computer science. I am a junior technical author here and passionate about Programming and learning new technologies. I have worked in JAVA, HTML 5, CSS3, Bootstrap, and PHP.