How to Unstage a Deleted File in Git

There are cases when you want to remove files from the staging area. In this tutorial, you will find the right way of unstaging a deleted file.

To discard changes to a file in Git, you usually run the git checkout command:

git checkout -- <file>

But when the change you want to discard is deleting the file, the above command line will fail.

Let’s discuss how you can restore that one file without discarding other changes. Assume you need to undo the result of git rm <file>, which is followed by git add with -A or something like that.

Run the git reset command to restore the file status in the staging area (also called index):

git reset -- <file>

Check out a copy from the staging area with the git checkout command:

git checkout -- <file>
Use double dashes to instruct Git to check out a file, not a branch.

The git checkout Command

The git checkout command switches branches and restores working tree files. The git checkout -- <file> 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: --soft, --mixed, --hard. Each of the options corresponds to Git's three trees: the commit tree ( HEAD), 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 ( HEAD) changes and points to the currently checked out branch, and the last commit on it through that branch.

Do you find this helpful?

Related articles