git rm
Remove files from both your working directory and Git tracking, staging the deletion for commit.
You no longer need a file in your repository and want to delete it from version
control. git rm removes the file from both your working directory and the
staging area, preparing the deletion for your next commit. It's Git's way of
deleting files while keeping the repository aware of the change.
Running git rm filename.js deletes the file from your filesystem and stages
the deletion. Your next commit will record that the file was removed. This is
cleaner than manually deleting the file and then running git add, though both
approaches work.
If you've modified the file since the last commit and haven't staged those
changes, Git refuses to remove it (protecting you from accidentally losing
work). Use -f to force removal: git rm -f modified-file.js. Be careful with
this—the file and its uncommitted changes are gone.
Sometimes you want to stop tracking a file without deleting it from your
filesystem. This happens when you accidentally committed a file that should be
ignored, like a local configuration or secrets file. Running
git rm --cached secrets.env removes the file from Git tracking but leaves it
in your working directory. After committing this change and adding the file to
.gitignore, the file stays local but won't be tracked going forward.
To remove entire directories, add -r for recursive:
git rm -r old-directory/. This removes the directory and all its contents from
Git and your filesystem.
If you've already deleted files manually (using rm instead of git rm), Git
notices them as "deleted" in git status. You need to stage the deletions with
git add or use git rm on the deleted files (which seems odd but works) to
stage the removal. Many developers just use git add -A after deleting files,
which catches all changes including deletions.
In pull request workflows, removing files should be deliberate and explained in commit messages. If a PR deletes a module, reviewers want to understand why and verify nothing still depends on it. Clean deletions make codebases easier to maintain by removing dead code and obsolete files.
Understanding git rm means properly handling file deletions in Git. Instead of files mysteriously disappearing, deletions are tracked changes that appear in commits, making it clear what was removed, when, and by whom.
