DEV Community

shruti jain
shruti jain

Posted on

2 1

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! 🚀

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️