How to use git rm command?

In this tutorial, you will learn the usage of git rm command.

When you remove a file from your working directory using rm command, that file does not delete from your Git repository. Actually, it goes into a deleted state. To delete it, you have to run git rm command followed by git commit.

Note: git rm command works on the files that are being tracked by Git.

For your better understanding, the entire working of git rm command is shown as a state diagram.

How to use git rm command

Suppose you have created a cameras.html file that shows Nikon, Canon, Sony and other brands cameras sell by a store. If you run git status command, you will find that the file is untracked.

$git status
On branch master
Untracked files:
  (use "git add ..." to include in what will be committed)


nothing added to commit but untracked files present (use "git add" to track)

So, add it to a repo using git add cameras.html. After that, you need to commit it using git commit -m "Add products file".

$git add cameras.html
$git commit -m "Added cameras.html file."

Now, you will find that Git is tracking the file. Let's say the store has decided to stop selling cameras and wants to delete this file. The best way to remove the file is to use git rm command instead of rm command of the terminal. But, if you have deleted the file using rm then on running git status you will get the following output:

$rm cameras.html
$git status
On branch master
Changes not staged for commit:
  (use "git add/rm ..." to update what will be committed)
  (use "git checkout -- ..." to discard changes in working directory)

        deleted:    cameras.html

no changes added to commit (use "git add" and/or "git commit -a")

From the above output, you can see that the cameras.html file has been deleted. But it also shows that the changes are not staged. We have to make the deletion of cameras.html a part of commit by running git rm command.

$git rm cameras.html
$git status
On branch master
Changes to be committed:
  (use "git reset HEAD ..." to unstage)

        deleted:    cameras.html

You can see that the deletion of cameras.html is shown in the "Changes to be committed" section.

Next, you commit as usual: git commit -m "Remove cameras.html file". After that, run git status, and it will show you that the working directory is clean.

$git commit -m "Remove cameras.html file"
$git status
On branch master
nothing to commit, working directory clean

To ensure that the deletion has happened, run ls and you will find that cameras.html file has gone.

Note: Instead of using rm command, always use git rm command to delete files from your Git repository.