How to Untrack Files in Git Without Deleting Them

There are times when you want Git to stop tracking certain files—for example, configuration files, log files, or sensitive data—but you don’t want to delete them from your local machine. This process is called untracking, and it’s a critical skill for keeping your Git repository clean and secure.

In this guide, you’ll learn how to untrack files or folders in Git, without deleting them locally.


🧾 Why Untrack Files?

You may want to untrack files when:

  • You accidentally committed sensitive files (e.g., .env)
  • You no longer want Git to track temporary files (e.g., logs, debug data)
  • You want to clean up your Git history

✅ Step 1: Add the File to .gitignore

First, tell Git to ignore the file in future commits by adding it to .gitignore.

echo filename.txt >> .gitignore

If you want to ignore an entire folder:

echo folder-name/ >> .gitignore

⚠️ Adding a file to .gitignore only prevents future tracking—it doesn’t untrack files already committed.


✅ Step 2: Untrack the File Without Deleting It

To stop tracking a file but keep it locally, use:

git rm --cached filename.txt

If it’s a folder:

git rm -r --cached folder-name/

Then commit the changes:

git commit -m "Untrack filename.txt"
git push origin branch-name

📌 Example: Untrack .env File

echo .env >> .gitignore
git rm --cached .env
git commit -m "Stop tracking .env file"
git push origin main

🔍 How to Untrack All Ignored Files

If you’ve updated .gitignore and want to untrack all matching files:

git rm -r --cached .
git add .
git commit -m "Remove all ignored files from tracking"

This will untrack all currently tracked files and re-add only those not ignored.

⚠️ Use with caution—it resets the entire index.


📝 Summary

TaskCommand
Ignore a fileecho filename >> .gitignore
Untrack a single filegit rm --cached filename
Untrack a foldergit rm -r --cached folder/
Untrack all ignored filesgit rm -r --cached . (then git add .)
Commit untracking changesgit commit -m "Untrack files"

✅ Best Practices

  • Always test your .gitignore before untracking sensitive files
  • Use git status to review changes before committing
  • Avoid untracking shared files unless all contributors are aligned

Untracking files in Git is essential for maintaining a clean and secure codebase. With the right use of .gitignore and git rm --cached, you can keep your repo focused only on what matters.

Sharing Is Caring:

Leave a Comment