Git rm: remove files from the repository
git rm removes a file from the Git repository. With --cached, it untracks the file without deleting it from disk. Essential for cleaning up your project.
What is git rm?
git rm removes a file from the Git repository. Unlike a simple rm, Git records the deletion and stages it for the next commit.
The most common use case: removing a sensitive file (.env, credentials) added by mistake with git rm --cached.
Git rm syntax
git rm fileRemove from repo and from disk
git rm --cached fileUntrack but keep on disk
git rm -r directory/Remove a directory recursively
Git rm in practice
Remove files or untrack them.
Remove a file
Untrack (--cached)
git rm vs rm vs .gitignore
git rm
Removes from the Git repo and from disk. The deletion is staged.
git rm --cached
Removes from Git tracking but keeps the file on disk.
.gitignore
Prevents Git from tracking files not yet tracked. Does not affect files already tracked.
Common mistakes with git rm
Adding .env to .gitignore but forgetting git rm --cached
.gitignore does not affect files already tracked. You must first run git rm --cached .env then add .env to .gitignore.
Using rm instead of git rm
If you delete with rm, Git sees the change but does not stage it. You then need to run git add to stage the deletion.
Forgetting the file remains in history
git rm removes the file from the next commit, but it still exists in previous commits. For a secret, you need to rewrite history.
Part of the Git Advanced guide
GitQuest is created by Anaïs (nouvelle fenêtre), web developer and head of education, specializing in tech training and digital accessibility.
Questions about git rm
Learn to manage your files with GitQuest
GitQuest investigations teach you to clean up and organize your repository.
Start the investigations