Delete a file from a Git repository
Remove a tracked file with git rm, keep a local copy with --cached, undo a staged deletion, and understand what remains in repository history.
Run git rm -- file and commit the deletion to remove a tracked file from the current version of a repository. To keep the file on your computer while removing it from the index, use git rm --cached instead.
Choose what to remove
# Delete the file and stage its removal.
git rm -- old-file.txt
git commit -m "Remove obsolete file"
For a local configuration file that should no longer be tracked:
git rm --cached -- config.local.js
# Add config.local.js to .gitignore, then stage that rule.
git add .gitignore
git commit -m "Stop tracking local configuration"
For a directory, use git rm -r --cached -- node_modules/. These cached removals preserve your working-tree copies. Once the deletion commit reaches teammates, their tracked copies can be removed when they update, so coordinate configuration migrations.
If you already deleted a file through an editor or file manager, stage the deletion explicitly:
git add -- old-file.txt
git commit -m "Remove obsolete file"
git add -A also records deletions, but includes other changes in its scope.
A deletion commit does not erase history
Older commits still contain the file. If it exposed a credential, revoke or rotate that credential first. Removing historical copies requires a separate, coordinated history rewrite. For example, in a fresh disposable clone, the separately installed git-filter-repo can remove a path:
git filter-repo --path secrets.env --invert-paths
Account for every historical path and affected branch or tag. Publishing rewritten history requires deliberate non-fast-forward updates and coordination with other clones; a bare git push --force is not a complete cleanup procedure. Forks, cached views, and downloaded copies may still exist. Follow your hosting provider's sensitive-data removal procedure.
FAQ
Why does git rm refuse a modified file?
The check protects uncommitted work. Inspect or save it first. git rm -f -- file overrides the check and discards the local file when that is intentional.
How do I undo an accidental deletion?
If you only deleted the working-tree file, use git restore -- file. If git rm staged the deletion, restore both locations from HEAD:
git restore --source=HEAD --staged --worktree -- old-file.txt
After a deletion has been committed, restore from a commit that still contains the file, then stage and commit it. HEAD~1 is suitable only when that specific parent has the version you need.
Can I delete a file on GitHub?
Yes. The file menu offers a deletion action, followed by a commit or pull-request workflow depending on permissions and branch rules.
See git-rm, git-restore, the git-filter-repo manual, and GitHub file deletion.
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan