To delete a file from a Git repository, follow these steps:
1. Remove the File from Git
Use git rm
to delete the file from the working directory and stage the deletion:
git rm filename.txt
- If the file was already deleted manually (e.g., via
rm filename.txt
), stage the deletion with:
git add -u # Stages all deleted/modified files
2. Commit the Change
git commit -m "Remove filename.txt"
3. Push to Remote Repository
git push origin branch-name
Example Workflow
# Delete and stage the file
git rm old-file.txt
# Verify changes
git status # Shows "deleted: old-file.txt"
# Commit and push
git commit -m "Remove old-file.txt"
git push origin main
Key Notes
- Remove from History (Advanced):
If the file needs to be completely purged from Git history (e.g., sensitive data), use tools like:
git filter-repo --path filename.txt --invert-paths
or the BFG Repo Cleaner.
⚠️ Warning: Rewriting history affects collaborators.
- Keep File Locally:
To remove the file from Git but keep it in your working directory, use:
git rm --cached filename.txt
Summary
Step | Command | Action |
---|---|---|
Delete & Stage | git rm filename.txt | Removes file and stages deletion |
Commit | git commit -m "message" | Finalizes removal in Git history |
Push | git push | Updates remote repository |