How do I remove a file or folder from a repository without deleting it from my local machine? #212061
🏷️ Discussion TypeQuestion BodyI accidentally committed node_modules and a .env file. How can I stop tracking them in Git while keeping them locally, and how do I make sure they’re never committed again? |
Replies: 1 comment
|
git rm -r --cached node_modules --cached removes the files from Git only, not from your disk. .gitignore only affects untracked files, which is why you must untrack them first. Important: If .env held real secrets (API keys, DB passwords), they’re still in the old commit history. Rotate those secrets immediately, then optionally purge history with git filter-repo or BFG Repo-Cleaner. Commit a .env.example with dummy values so others know which variables are needed. |
git rm -r --cached node_modules
git rm --cached .env
echo "node_modules/" >> .gitignore
echo ".env" >> .gitignore
git add .gitignore
git commit -m "chore: stop tracking node_modules and .env"
git push
--cached removes the files from Git only, not from your disk. .gitignore only affects untracked files, which is why you must untrack them first.
Important: If .env held real secrets (API keys, DB passwords), they’re still in the old commit history. Rotate those secrets immediately, then optionally purge history with git filter-repo or BFG Repo-Cleaner. Commit a .env.example with dummy values so others know which variables are needed.