Git - What is the difference between rm and git rm?
This article covers how to use the command ‘git rm’.
If you want to remove files on a Unix (or Unix-like) operating system, you can open the shell and use the rm command.
This would delete the file from the filesystem.
However, if the file is staged in git, then it would not track the deletion in the staging area.
To do this, you simply need to stage your deletion:
rm <file-name>
git add <file-name>
It’s confusing to use add when you’re trying to delete a file. In this instance, you are adding the file deletion changes into the staging area, so that the file is deleted when you next commit.
Using git rm
A simpler method would be to use the command git rm
git rm <file-name>
This would remove the file from your working directory, and stage it automatically.
—f
What if you have staged changes? You can simply force the removal with the -f parameter:
git rm -f <file-name>
This will remove all the working changes you have made on that file.
—cached
Alternatively, you could keep all of your working changes locally, but still move the deleted file into your staging area. This is done using the —cached parameter:
git rm --cached <file-name>
After running this command and committing, the file will be deleted on the remote repository, but the full file will still be in your working directory.
In fact, the file in your working directory will now be considered a new file, and therefore untracked.
—dry-run
If you want to see what commands git would run, without deleting any files, you can add the —dry-run parameter:
git rm --dry-run <file-name>
Removing a Directory
To remove an entire directory and all of its contents, use the -r parameter for recursive removal:
git rm -r <directory-name>
This will remove the directory from your working directory and stage the deletion, just like git rm does for a single file.
Undo git rm
If you haven’t committed yet, you can undo a git rm by restoring the file from HEAD:
git checkout HEAD -- <file-name>
If you used git rm —cached, the file is still in your working directory, so no undo is needed. The file simply becomes untracked.
git rm vs git restore
In modern Git (2.23+), you can use git restore to unstage a deletion instead of git checkout:
git restore --staged <file-name>
This achieves the same result but with a clearer intent. The git restore command was introduced to separate the responsibilities of git checkout, making it easier to understand what each command does.