In this blog, we will elaborate on the procedure of restoring deleted files in Git.
Can Git Restore a File?
Yes, Git can restore a file. This operation seems necessary in a situation where you mistakenly removed any important file which is required to restore.
How to Restore a File in Git?
In the below-given procedure, first, we will move to a Git repository and check the list of existing files. Then, select any one of them, and remove it using the “$ git rm <file-name>” command. After that, unstage the deleted file and execute the “$ git checkout — <file-name>” command to restore it.
To understand the above-discussed scenario, check out the below-provided steps!
Step 1: Navigate to Git Directory
Firstly, move to the Git local repository using the “cd” command:
Step 2: List Repository Files
Run the “git ls-files” command to view all files of the specified repository:
As you can see, our “demo2” Git repository contains three files, two with “.txt” and one with “.rtf” extension:
Step 3: Remove File
Now, we will remove the “demo1.txt” file from the Git local repository with the help of the “git rm” command:
Here, our specified file is deleted successfully:
Step 4: List Repository Files
Execute the provided command to verify the file removing operation:
As you can see in the below output, there is no file exist with name “demo1.txt”:
Step 5: Check Status
Check the current status of the Git Repository by utilizing the “git status .” command:
The deleted file is staged automatically, which is the default behavior of the “rm” command:
Step 6: Unstage File
Next, unstage the deleted file by executing the “git reset” command:
Here, specify the “HEAD” option with the file name to unstage the changes:
Step 7: Check Status
Run the below command to check the status:
As you can see, the delete changes are now unstaged:
Step 8: Restore File
Finally, execute the “git checkout” command to restore the file:
Again, execute the “git status .” command to view the Git repository current status:
Nothing is placed in the repo which needs to commit, and the working area is clean:
Step 9: Verify Restore File
Lastly, list the repository files to view the restored file:
The given output shows that we have successfully restored the deleted “demo1.txt” file to our Git repository:
We have presented the method of restoring a file.
Conclusion
Yes, you can restore the file in Git. To do so, move to the Git local repository, and check the existing files which are placed in the repository. Next, run the “$ git rm <file-name>” command to remove any file. Then, unstage the changes using the “$ git reset HEAD — <file-name>” command. Lastly, execute the “$ git checkout — <file-name>” command to restore the removed file. This blog explained the procedure of restoring deleted files in Git.