As a part of GIT Tutorials End To End, we will learn about retrieving a deleted but not committed file in Git.
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.
Retrieving A Deleted File in Git
Deleting a file is not a rare action while working on a project but sometimes it might be accidental. There are multiple scenarios in this but we will focus on retrieving a deleted file but the result is yet to be committed. Let’s do this in action to understand better.
I have created a git project and added and committed a file. This project is not linked to any remote repository i.e. all changes are local.
Now we will delete the file “fileA.txt” but we will not commit this action.
In this scenario, we can retreieve deleted file from last commit. We know that HEAD will point to the last commit. So we can use the below command –
git checkout HEAD <fileName>
As you can see in the above screenshot we have recovered deleted file. But what have we done here? We have retrieved the file from history i.e. commit. What if we have made some changes to the file after the last commit? Let’s see below –
I have added a new line in the file and then deleted it. Let me try to recover it as done previously.
We got the file back but the content is exactly the same as we had at the last commit. Changes made after the last commit is gone. So we are retrieving the file from a stage.
Using the git command line, as far as I know, it is difficult to get changes back but if you are using IDE such as Eclipse, and IntelliJ then we can get the changes back using local history.
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.