Delete Files – git rm

Deleting Files with git rm

The git rm command can delete a file in the Working Tree and register the status in INDEX (Staging Area). To reflect it in the commit history, you need to run the git commit command afterward.

The typical command flow is as follows.

To delete a file (No option)

When you delete a file, you don't need to add an option.

git rm [ file path ]
git commit

To delete a directory (with the "-r" option)

If you want to delete a directory, you need to use the -r option before the directory path.

git rm -r [ directory path ]
git commit

Practice

bloovee-round-icon.pngDeveloper A (Project Owner Role)

Objective:
Check how the git rm command works

1. Prepare a file to delete

For this practice purpose, create a copy of the git_practice.html file and commit the new file. Run the cp command and commit the file as shown below.

Command Line - INPUT
cp git_practice.html git_practice_copy.html
git add .
git commit -m "Added a new file"

2. Delete the file

To delete the file run the git rm command and check the status with the git status command.

Command Line - INPUT
git rm git_practice_copy.html
git status

After running the command above, you can see the following response

Command Line - RESPONSE
On branch master
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        deleted:    git_practice_copy.html

To register the status in the Local Repository, run the git commit command. And check the latest commit log.

Command Line - INPUT
git commit -m "Deleted the new file"
git log --oneline

You can confirm that the deleted status is already registered in the commit histories as shown below.

Command Line - RESPONSE
[master a2db148] Deleted the new file
 1 file changed, 13 deletions(-)
 delete mode 100644 git_practice_copy.html
a2db148 (HEAD -> master) Deleted the new file
ad09fe6 Added a new file
651e510 the first commit

The demo code is available in this repository (Demo Code).