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

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.

  1. Remove the file from Git index

    Use the --cached option to untrack the file:

    git rm --cached .env
    • --cached tells 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".
  2. Add the path to .gitignore

    Prevent Git from tracking it in future commits:

    echo ".env" >> .gitignore
    # For folders:
    echo "config/" >> .gitignore
    On Windows PowerShell, use Add-Content instead: Add-Content .gitignore ".env".
  3. 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 .gitignore but it’s still tracked.”
    Files already tracked need to be untracked first with git rm --cached <path>.
  • “My teammates still see the file tracked.”
    Make sure you git push after committing the removal so everyone gets the update.
  • “I only want to ignore .env in this project.”
    Use the project .gitignore (as shown). For global ignores across all repos, configure a global ignore file with git config --global core.excludesfile ~/.gitignore_global.
Built with ❤️ for developers who like clean repos and safe secrets.

Comments

Popular posts from this blog

Top Laravel Security Best Practices: How to Secure Your Web Application 🚀

Restoring Your Data in Xampp: A Step-by-Step Guide

Passing array from child to parent component