How to Remove a File from a Git Commit: A Practical Guide
Mistakenly committed a file to Git? Whether it’s a .env file with sensitive information, a large log file, or simply the wrong version of a document — it happens to the best of us.
Fortunately, Git gives you powerful tools to remove a file from a commit — whether the commit is staged, local, or already pushed. In this guide, we’ll walk you through several scenarios and how to fix them properly.
🔍 Scenario 1: File Was Just Added, But Not Yet Committed
If you staged the file using git add, but haven’t committed yet:
✅ Solution: Unstage the File
git reset HEAD <file-name>
Then, if you also want to remove it from your working directory:
rm <file-name>
🔍 Scenario 2: File Committed, But Not Yet Pushed
If you already made the commit, but haven’t pushed it to a remote repository:
✅ Solution: Amend the Last Commit
First, remove the file from Git tracking:
git rm --cached <file-name>
Then amend the last commit:
git commit --amend
This will open your default text editor. Save and close to confirm the updated commit without the file.
⚠️ Note: This rewrites your commit history. Only do this before pushing.
🔍 Scenario 3: File Is in a Previous Commit, and You’ve Already Pushed
If the file is already part of a pushed commit and you need to completely remove it from the repository (e.g., for security reasons):
✅ Solution: Use git filter-repo (Recommended over filter-branch)
First, install git-filter-repo (requires Python):
https://github.com/newren/git-filter-repo
Then, run:
git filter-repo --path <file-name> --invert-paths
This will completely remove the file from all commits in history.
After that:
git push --force
⚠️ Use --force carefully — this rewrites history and affects collaborators.
🛡️ Add the File to .gitignore
To prevent accidentally committing the file again in the future:
Open (or create) a .gitignore file in your repo root.
Add the file name or pattern:
# Ignore sensitive file
.env
Save and commit the .gitignore file.
✅ Summary Table
Situation
Solution
Staged but not committed
git reset HEAD <file>
Committed but not pushed
git rm --cached <file> + --amend
Already pushed & sensitive
Use git filter-repo + git push --force
Prevent future commits
Add to .gitignore
Final Thoughts
Removing a file from a Git commit isn’t difficult, but choosing the right method for your situation is crucial. Always double-check what’s being committed — and when mistakes happen, Git has your back with flexible solutions.