What is `git rm` used for?
git rm is used to remove files from a Git repository while recording that removal for the next commit.
That is, the command:
- removes the file from the working directory
- adds the removal to the staging area
How git rm differs from plain rm
| Action | File removed | Git knows about the removal |
|---|---|---|
rm file.txt | yes | no (needs git add) |
git rm file.txt | yes | yes |
Basic usage
bash
git rm file.txt
git commit -m "Remove unused file"Main variants
1. Remove a file from the project completely
bash
git rm src/old.js2. Remove a file only from Git (keep it on disk)
bash
git rm --cached config.envUseful when:
- a file ended up in the repository by mistake
- it needs to be added to
.gitignore
3. Remove a directory
bash
git rm -r dist/Common use cases
- Removing outdated files
- Removing secrets from a repository
- Cleaning up unnecessary artifacts from a project
- Refactoring project structure
Frequent mistakes
- Using
rminstead ofgit rmand forgettinggit add - Removing a file without committing
- Removing an important file without
--cached
Checking the state
After removal:
bash
git statusShows:
text
deleted: src/old.jsShort answer for an interview
git rmremoves a file from the working directory and at the same time stages its removal for a commit in Git.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.