How to Revert "git rm -r"

As we know, the git rm command removes a file or a folder from the working directory and adds that change to the staging area. But, sometimes, developers call it accidentally or give a wrong file as an argument. Here, we will demonstrate how to act in such cases.

Watch a course Git & GitHub - The Practical Guide

Steps to reverting git rm -r

Below, you will find several options on how to restore deleted files or folders.

Reverting git rm with the git checkout command

First, you should execute the git reset command to revert the current staging area.

git reset

After running git reset, you can run git checkout to restore the removed file/folder.

git checkout <file-name>

Instead of reverting the staging area and checking out the deleted file, we can use a single command to meet the same goal:

git checkout HEAD <file-name>

Reverting git rm with the git reset command

If there are no important uncommitted changes, then run git reset with the --hard option which will reset everything to your latest commit:

git reset --hard HEAD

The git rm Command

The git rm command is executed to remove specific files or a group of files from a git repository. The primary function of git rm is removing tracked files from the staging area and also from the working directory. However, a file can not be deleted only from the working directory. It is essential to mention that the git rm command is not used for removing branches. The command updates the staging area and the working directory. These changes will not be persisted until a new commit is created. The changes are included in the commit history, meaning that they can be undone with other git commands.

The --hard Option

The --hard option is the most commonly used option of git reset. However, it has some risks. With this option, the commit history reference pointers start pointing to the stated git commit. Next, the staging area and the working directory are reset to match the stated commit. Changes previously pending to the staging area and the working directory are reset to correspond to the commit tree state. Any pending commit in the staging area and working directory will be lost.

The git checkout Command

The git checkout command is used for switching branches or restoring the files of the working tree. It can be applied on files, commits, as well as branches. In short, the git checkout command allows you to switch between multiple features in just a single repository. It is essential to state that git checkout operates with the git branch command. It updates the files in the working directory to match the version kept in that branch telling Git to record all the new commits. Also, git checkout is associated with the git clone command. And, finally, note that git clone fetches the code from a remote repository whereas git checkout is aimed at switching code versions on the local system.