DEV Community

shruti jain
shruti jain

Posted on

Removing a Tracked File from Git After Adding It to .gitignore

Sometimes, we accidentally commit files that should have been ignored, like config/config.js, .env, or node_modules/. Adding them to .gitignore after committing doesn’t remove them from Git's history. Here’s how you fix it properly.

Step 1: Add the File to .gitignore

First, make sure the file is listed in .gitignore.

# Ignore config file
config/config.js
Enter fullscreen mode Exit fullscreen mode

Step 2: Remove the File from Git Tracking

Since Git is already tracking the file, we need to untrack it without deleting it from the local system.

Run this command:

git rm --cached config/config.js
Enter fullscreen mode Exit fullscreen mode

✅ This removes it from Git without deleting it locally.

Step 3: Commit and Push the Change

Now, commit this change:

git commit -m "Removed config.js from repo"
git push origin main  # Change 'main' if using a different branch
Enter fullscreen mode Exit fullscreen mode

From now on, Git will ignore config/config.js, and it won’t be included in future commits.


Bonus: Remove It from Git History (If Already Pushed)

If the file was already pushed and contains sensitive data, you need to rewrite Git history:

git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch config/config.js' \
--prune-empty --tag-name-filter cat -- --all
Enter fullscreen mode Exit fullscreen mode

Then force push the changes:

git push origin --force --all
Enter fullscreen mode Exit fullscreen mode

Warning: This rewrites history, so be cautious if working in a shared repository!


Now your secret files are safe, and Git will ignore them in the future! 🚀

Top comments (0)