How to Remove a File from Git

Sometimes you commit a file to Git that you no longer want to track—whether it’s an outdated script, a sensitive file added by mistake, or just unnecessary clutter. Fortunately, Git makes it easy to remove files from both the repository history and your local working directory (or just from tracking).

This guide covers several ways to remove files from Git depending on your use case.


✅ Option 1: Remove a File from Git and Local Disk

If you want to delete the file from both Git and your computer:

git rm filename.txt
git commit -m "Remove filename.txt"
git push origin branch-name

What it does:

  • Deletes filename.txt from your local disk
  • Stages the removal for commit
  • Removes it from the repository after push

✅ Option 2: Remove a File from Git, Keep Locally

If you want Git to stop tracking the file but keep it locally:

git rm --cached filename.txt
git commit -m "Stop tracking filename.txt"
git push origin branch-name

When to use:

  • Removing sensitive or temporary files (e.g., .env, logs)
  • Adding files to .gitignore after they’ve already been committed

👉 After this, you should add the file to your .gitignore so it doesn’t get accidentally re-added:

echo filename.txt >> .gitignore

🔁 Option 3: Remove a Folder from Git

You can also remove entire folders using:

git rm -r folder-name
git commit -m "Remove folder-name"
git push origin branch-name

Add --cached if you want to keep the folder locally but untrack it from Git.


🧼 Option 4: Remove File from Git History (Advanced)

If you’ve committed a sensitive file (e.g., a password or API key) and need to remove it from Git history, use BFG Repo-Cleaner or:

git filter-branch --force --index-filter \
"git rm --cached --ignore-unmatch filename.txt" \
--prune-empty --tag-name-filter cat -- --all

⚠️ This rewrites history. Be careful and avoid this on shared/public branches unless necessary.


📝 Summary

TaskCommand
Remove file completelygit rm filename.txt
Untrack file but keep locallygit rm --cached filename.txt
Remove foldergit rm -r folder-name
Remove from history (advanced)git filter-branch or BFG Repo-Cleaner

Removing files in Git isn’t just about deletion—it’s about control. Whether you’re cleaning up your repo, updating tracked files, or protecting sensitive data, the right removal method ensures a clean and secure project history.

Sharing Is Caring:

Leave a Comment