So you want to remove a file from a Git repo. Good choice when it is junk, bad choice when it is your config file that you forgot was important. This quick git tutorial will show how to check whether a file is tracked, remove a file from the repository or just stop tracking it while keeping a local copy, and how to rescue a file if you panic later.
Inspect the repo state first
Before you blithely delete things and create a merge conflict of doom, run a couple of checks to see what Git thinks.
git status
git ls-files | grep filename
git status shows staged and unstaged deletions. Use git ls-files to see if that filename is actually tracked by Git or if it is just lying around in your working directory.
Remove a tracked file from disk and history
If you want the file gone from both the repo and the working tree use the classic command.
git rm path/to/file
git commit -m "Remove unwanted file from repository"
git push origin main
This makes the file disappear from the next commit and pushes the removal to the remote branch. Replace origin and main with your remote and branch names if your repo enjoys being special.
Stop tracking a file but keep it locally
If the file contains local configuration or build artifacts you do not want in the repo but you still need it on your machine use git rm --cached. That untracks the file without deleting your local copy.
git rm --cached path/to/file
# add the filename or pattern to .gitignore
echo "path/to/file" >> .gitignore
git add .gitignore
git commit -m "Stop tracking local config"
git push origin main
Adding the pattern to .gitignore prevents future accidental commits of the same file. This is the tidy version of cleanup for people who like clean diffs and less noise in version control.
Recover a deleted file if you made a mistake
Mistakes happen. Git is forgiving if you act before you rewrite history.
git restore --source=HEAD^ -- path/to/file
# or for older Git versions
git checkout HEAD^ -- path/to/file
# then
git add path/to/file
git commit -m "Restore file accidentally removed"
git push origin main
HEAD^ refers to the previous commit. Those commands pull the file from the last commit where it existed and let you recommit it if you want tracking to continue.
Quick checklist
- Run git status and git ls-files to see if a file is tracked
- Use git rm to delete from repo and disk
- Use git rm --cached and .gitignore to stop tracking but keep local copy
- Use git restore or git checkout to recover accidental deletions
- Commit with a clear message and git push to update the remote
Version control is supposed to save you not haunt you. Use git rm and git rm --cached thoughtfully, keep your .gitignore updated, and commit descriptive messages so your future self does not send angry emails to present self.