Git Tutorial 32 – How To Restore Deleted And Committed But Not Pushed File Without GIT Reset?

Introduction

As a part of GIT Tutorials End To End, we will learn about retrieving a deleted and committed file in Git without using GIT reset command.

Prerequisite posts

I will expect that you are aware of the basic concepts and commands of GIT. But if you are a beginner in GIT then I strongly recommend you to refer GIT Basic Commands and Concepts section on my blog first.

Previously we learned How To Retrieve Deleted But Not Committed File In Git.

Retrieving A Deleted and committed File in Git

In the previous post, we deleted the file but did not commit it. In this post, the scenario will be a little different. I will delete the file and will commit it as well. Please note that the commit will be local and will not be pushed to the remote repo.

Retrieving A Deleted and Committed File in Git

Let’s create a GIT repository and some files with contents.

Add and commit.

Now let’s delete a file and commit the change i.e. deletion.

In the previous post, we recovered the deleted file using the checkout command because the deleted file was not committed. Let’s run the same command again in this scenario.

We will see an error as above. As I have explained in my previous post that deleted file is recovered from the last commit i.e. HEAD. We have deleted the file but the deletion was not committed. So HEAD was still pointing to the commit in which deleted file was present. In this post, we have deleted the file and also committed the changes. Committing the changes will create a new commit id and HEAD will point to that. So when we used the checkout command in this condition, GIT tries to recover the file from the latest commit i.e. HEAD but the latest commit does not have that file because the latest commit actually has changes to delete the file.

So can we try to recover a deleted file from another commit rather than the HEAD? Yes, we can do it.

List out all commits.

We know that commit id 9928269 which is HEAD currently has changes in which we deleted the file. The commit id d240dca is the stage at which my deleted file was present. So we can retrieve the deleted file from stage i.e. commit id d240dca. We just need to use this commit id instead of HEAD.

So we are able to recover the deleted file. You need to commit this change i.e. retrieval.

You can see in the above screenshot that we still have the commit id in which the file was deleted. We have another way of retrieving the deleted file which will omit the commit history as well. We will see that in the next post.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe to my YouTube channel.
#ThanksForReading
#HappyLearning

Leave a Reply

Your email address will not be published. Required fields are marked *