How to Undo rm in Git

Abdul Jabbar Feb 02, 2024
  1. Remove File in Git
  2. Revert rm Command Using Git checkout Command:
  3. Revert rm Command Using Git reset Command
How to Undo rm in Git

In Git, the term rm is an alias for the git remove command. So it is used for removing individual files or a bunch of files from the repository. The main feature of git rm in Git is to remove tracked files using the Git index.

However, git rm can also be used to remove files from both the working directory and the index. It removes files from the current working directory and its subdirectories within the same branch. It will not remove files outside the current working directory. It is important to mention that the git rm command is not used to delete branches in a repository.

Remove File in Git

To remove individual files from the Git index, we use the following command:

$ git rm <file>

Similarly, to remove a bunch of files from Git, we use the following command.

$ git rm <file> <file> <file> ...

And if we wish to remove a file from the working directory, we use the following command:

$ git rm --cached <file>

While git rm --cached deletes the file from the working directory, it does not remove it from the Git index.

But in this article, we state what to do if we accidentally applied this command, and now we want to revert it. The below-mentioned way is the easy way to revert the changes. Git has lots of commands to recover it. I think it would be better to cover the ones we are going to use the most in the following portion:

Revert rm Command Using Git checkout Command:

Firstly, we will execute the command git reset to revert the staging area to the changes we did.

git reset

After applying git reset, we will run git checkout to restore the removed file or folder from the last check-in in the same repository.

git checkout <file-name>

if we don’t want to revert the staging area and check out the removed file, we can execute it in a single step easily by mentioning head with it to meet the desired goal as follows:

git checkout HEAD <file-name>

Revert rm Command Using Git reset Command

If we have no important uncommitted changes, then we will run git reset with the --hard option which will reset each and everything to our latest commit in the branch:

git reset --hard HEAD

If we have uncommitted changes, but the first git command doesn’t work, then we will save our uncommitted changes with git stash:

git stash
git reset --hard HEAD
git stash pop
Author: Abdul Jabbar
Abdul Jabbar avatar Abdul Jabbar avatar

Abdul is a software engineer with an architect background and a passion for full-stack web development with eight years of professional experience in analysis, design, development, implementation, performance tuning, and implementation of business applications.

LinkedIn

Related Article - Git rm