git rm
Remove files from the working tree and the staging area
The 'git rm' command deletes a tracked file and stages the deletion, so the next commit no longer contains it. Older commits keep the file. With --cached, Git stops tracking the file but leaves it on your disk — the usual fix for a file committed by mistake. git rm refuses to delete a file with uncommitted changes unless you add -f.
Synopsis
git rm [-f | --force] [-n] [-r] [--cached] [-q] [--] <pathspec>...Options
Choosing the Right Option
Ways to remove a file
What happens on disk and in Git
| Command | On disk | In the next commit |
|---|---|---|
rm file | Deleted | Still there until you stage the deletion |
git rm file | Deleted | Removed |
git rm --cached file | Kept | Removed (file becomes untracked) |
Examples
Delete a file
git rm old.jsDeletes old.js and stages the deletion.
Stop tracking
git rm --cached .envGit forgets .env; the file stays on disk.
Delete a folder
git rm -r build/Deletes a folder and its tracked files.
Workflow Examples
git rm --cached .envStop tracking it, keep it on disk
echo ".env" >> .gitignoreIgnore it from now on
git add .gitignoreStage the ignore rule
git commit -m "Stop tracking .env"Commit
Troubleshooting
error: the following file has local modifications
Cause: The file has changes that are not committed
Commit or stash them, use --cached to keep the file, or -f to discard them
fatal: not removing 'dir' recursively without -r
Cause: The path is a folder
Add -r: git rm -r dir
A secret is still in the history
Cause: git rm only affects future commits
Rotate the secret; rewriting history needs a tool like git filter-repo
Tips & Pitfalls
Best Practices
- ✓Use git rm instead of rm + git add: one step, nothing forgotten.
- ✓Add untracked files to .gitignore right after git rm --cached.
- ✓Treat a committed secret as leaked: change it, even after removing the file.
Common Mistakes
- ✗Deleting a file with plain rm and forgetting to stage the deletion.
- ✗Using git rm when you only wanted to stop tracking: add --cached to keep the file.
- ✗Expecting git rm to remove a secret from history — older commits still contain it.
FAQ
Stage the deletion with git rm <file> or git add <file>, then commit.
Before committing: git restore --staged --worktree <file>. After: git restore --source=<commit> <file>.
No. Past commits keep it; only the next commit drops it.