How to Revert “git rm -r ”

If you execute git rm. by chance and want to revert it, then we suggest two cases described in detail to give answer to your question.

Execute the git reset command to revert the current staging area and working directory back to the HEAD commit:

git reset HEAD

If there are not any uncommitted changes that are important then invoke git reset with the --hard option which will reset everything to your last commit:

git reset --hard HEAD

If there are uncommitted changes, but running git reset doesn't work, you can save these changes with the git stash command:

git stash

git reset --hard HEAD

git stash pop

If you want to revert a single git rm rather than an entire recursive git rm -r we suggest the following solution:

git checkout HEAD path/to/file path/to/another_file

This solution better suits the situation when you git rm some files, make changes before the next commit, and accidentally realized that you need to get back some of those files. You can check out the single files you missed or removed if you want.

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 stash Command

The git stash is executed to stash the changes added to the index (staged changes) and changes made to files currently tracked by Git (unstaged changes). The git stash pop removes the changes from your stash and re-applies them to your working copy. The alternative of git stash pop is running git stash apply to re-apply the changes and keep them in your stash.


Do you find this helpful?

Related articles