Version control is all about tracking changes, but sometimes you need to remove files entirely—whether due to accidental commits, outdated assets, or sensitive information. Deleting a file from a remote Git repository is a common task, and doing it correctly ensures a clean and traceable history.
In this guide, we’ll walk you through the steps to safely delete a file from your Git repository and push that change to the remote (e.g., GitHub, GitLab, Bitbucket).
Why You Might Need to Delete a File
Common scenarios include:
- Removing large or unnecessary files
- Eliminating hardcoded secrets or credentials
- Cleaning up legacy assets
- Fixing incorrect commits
⚠️ If the file contains sensitive data (like passwords or API keys), a regular deletion won’t remove it from history. For that, see the “Bonus” section on removing sensitive data.
Step-by-Step: Deleting a File from Remote Git
✅ Step 1: Clone or Navigate to Your Repository
If you haven’t already, clone your repository or navigate to the local project directory:
git clone https://github.com/your-username/your-repo.git
cd your-repo
Or if you’re already in the repo:
cd path/to/your-repo
✅ Step 2: Delete the File Locally
Use the git rm
command to remove the file and stage the deletion:
git rm path/to/your-file.txt
Alternatively, if you delete the file manually (via Finder or File Explorer), you can stage the deletion with:
git add -u
✅ Step 3: Commit the Change
Now commit the deletion with a clear message:
git commit -m "Remove unnecessary file: your-file.txt"
✅ Step 4: Push the Changes to Remote
Send the updated repository (with the file removed) to the remote origin:
git push origin main
Replace main
with your branch name if different.
Verifying the Deletion
Once pushed, go to your remote repository (e.g., GitHub) and confirm the file has been removed in the latest commit. You can also use:
git log -- path/to/your-file.txt
This will show the history related to the deleted file (up to the point it was removed).
🔒 Bonus: How to Remove a File from Git History (Sensitive Data)
If you’ve accidentally committed sensitive information (like credentials), removing it from the current commit isn’t enough. You must scrub it from the entire history using tools like:
git filter-repo
(recommended)git filter-branch
(older and more complex)- BFG Repo-Cleaner
Example using git filter-repo
:
git filter-repo --path your-file.txt --invert-paths
⚠️ After cleaning history, you’ll need to force-push:
git push origin --force --all
Only do this on private branches or repositories with caution — force-pushing rewritten history affects collaborators.
Conclusion
Deleting a file from your remote Git repository is a simple yet important task. Follow these steps:
- Remove the file locally with
git rm
- Commit the change
- Push to your remote branch
By maintaining a clean repo and understanding how Git handles files and history, you’ll keep your projects safe, efficient, and organized.