How to Remove a File or Folder from Git Without Losing It Locally
How to Remove a File or Folder from Git Without Losing It Locally
Safely untrack sensitive or noisy files (like .env) from your repository while keeping them on your machine.
When working on projects, you often have files that shouldn’t be tracked by Git, such as .env files containing
sensitive credentials or configuration data. Committing these files can expose secrets and clutter your repository. But what if they are already tracked?
You can safely remove them from Git while keeping them on your local machine. Here’s how.
-
Remove the file from Git index
Use the
--cachedoption to untrack the file:git rm --cached .env--cachedtells Git to remove the file from version control only, leaving it on your disk.
Untrack a folder (recursively)
git rm -r --cached config/Tip: If the path contains spaces, wrap it in quotes, e.g."My Secrets/.env". -
Add the path to
.gitignorePrevent Git from tracking it in future commits:
echo ".env" >> .gitignore # For folders: echo "config/" >> .gitignoreOn Windows PowerShell, use Add-Content instead:Add-Content .gitignore ".env". -
Commit and push the changes
git add .gitignore git commit -m "Remove .env from Git and ignore it" git push
✅ Outcome
The original file (e.g.,
.env) stays on your local machine.Git stops tracking it immediately.
Future changes won’t be committed accidentally.
Already pushed secrets? Consider rotating keys and removing sensitive data from commit history using tools like
git filter-repo or GitHub’s secret scanning & exposure guidance.
Common Pitfalls & Fixes
-
“I added it to
.gitignorebut it’s still tracked.”
Files already tracked need to be untracked first withgit rm --cached <path>. -
“My teammates still see the file tracked.”
Make sure yougit pushafter committing the removal so everyone gets the update. -
“I only want to ignore
.envin this project.”
Use the project.gitignore(as shown). For global ignores across all repos, configure a global ignore file withgit config --global core.excludesfile ~/.gitignore_global.
Comments
Post a Comment
What is your thought about this?