There are two ways of deleting files in Git. Whichever method you select, in the end, you have to run git commit
command to delete the file from your working directory.
You can visualize the entire process of removing files in Git using a state diagram.
Note: A file is being tracked by Git otherwise you won't be able to take advantage of git rm
command.
When you use rm
command, then the file goes into a deleted state, which you can confirm by running git status
command.
$rm index.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: index.html no changes added to commit (use "git add" and/or "git commit -a")
Here, the file that we want to delete is index.html
After that, run git rm filename
command to move the file to a staging area. In our case, the file is index.html
so the command will be git rm index.html
. When you run git status
command, you will get the following output:
$git rm index.html $git status On branch master Changes to be committed: (use "git reset HEAD..." to unstage) deleted: index.html
Finally, you have to run git commit
to ensure that the file is deleted from the Git repo.
$git commit -m "Remove index file"
On running git rm
command, the file is not deleted; actually, it goes into a staging area. After moving the file to the staging area, you have to run git commit
command to delete that file from a Git repository. Let's understand the entire process with the help of an example.
Suppose you want to delete index.html
file, so you must run git rm index.html
. After that, run git status
command to confirm that the file is in the staging area.
$git rm index.html $git status On branch master Changes to be committed: (use "git reset HEAD..." to unstage) deleted: index.html
Next, you have to run git commit
command to confirm the removal of the file from a Git repository.
$git commit -m "Delete index.html file"