git rm

Basic Snapshotting

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>...
[ ] optional| or<arg> placeholder... repeatable--flag option

Options

Click any option to expand

Beginner (2)

Remove the file from the staging area only. The file stays on disk as an untracked file.

RecommendedUntrack a file (e.g. committed by mistake) without deleting it

Example

git rm --cached .env

Delete even if the file has changes that are not committed. Those changes are lost.

When neededDeletes uncommitted changes with the file — they are lost

Example

git rm -f app.js

Choosing the Right Option

Ways to remove a file

What happens on disk and in Git

CommandOn diskIn the next commit
rm fileDeletedStill there until you stage the deletion
git rm fileDeletedRemoved
git rm --cached fileKeptRemoved (file becomes untracked)

Examples

Delete a file

git rm old.js

Deletes old.js and stages the deletion.


Stop tracking

git rm --cached .env

Git forgets .env; the file stays on disk.


Delete a folder

git rm -r build/

Deletes a folder and its tracked files.

Workflow Examples

1
git rm --cached .env

Stop tracking it, keep it on disk

2
echo ".env" >> .gitignore

Ignore it from now on

3
git add .gitignore

Stage the ignore rule

4
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

A:

Stage the deletion with git rm <file> or git add <file>, then commit.

A:

Before committing: git restore --staged --worktree <file>. After: git restore --source=<commit> <file>.

A:

No. Past commits keep it; only the next commit drops it.