How to Unstage a Deleted File in Git
This tutorial will give the answer to the question of unstaging a deleted file in Git in a right and easy way. Also, read about git checkout and git reset.
There are cases when you have deleted a file and add the deletion to the staging area. Here, we will discuss how to unstage the deletion and restore the deleted file.
Steps to unstaging a deleted file
Let’s discuss how to restore that one file without discarding other changes. Assume you need to undo the result of git rm <kbd class="highlighted"> XFI2 </kbd>.
Unstaging the deleted file
Now, you need to unstage the deleted file with the git reset command as follows:
restore the file status, git reset
git reset -- <file-path>Undoing the deletion
Here, you need to run the git checkout command to restore the deleted file:
discard changes to a file in git, git checkout
git checkout -- <file-path>Use double dashes to instruct Git to check out a file, instead of checking out to a branch.
The git checkout Command
The git checkout command switches branches and restores working tree files. The <kbd class="highlighted">git checkout</kbd> <kbd class="highlighted"> -- <file> </kbd> command is used to discard changes in the working directory. However, take into account that this command is dangerous. Any local changes you made to that file are gone. Do not use this command until you are sure you do not need these unsaved local changes.
The git reset Command
The git reset command is a complex tool used to undo changes. It has three basic forms of invocation. These forms correspond to the command line options: <kbd class="highlighted">--soft</kbd>, <kbd class="highlighted">--mixed</kbd>, <kbd class="highlighted">--hard</kbd>. Each of the options corresponds to Git's three trees: the commit tree (<kbd class="highlighted">HEAD</kbd>), the staging area (index), and the working directory. The working directory represents the files on the file system of the computer available to the code editor for applying changes. The staging index tracks the changes committed in the working directory. The commit history (<kbd class="highlighted">HEAD</kbd>) changes and points to the currently checked out branch, and the last commit on it through that branch.