0
0
GitHow-ToBeginner · 3 min read

How to Remove a File from Git but Keep It Locally

Use git rm --cached <filename> to remove a file from Git tracking but keep it on your local disk. This command stops Git from tracking the file without deleting it locally.
📐

Syntax

The command to remove a file from Git tracking but keep it locally is:

  • git rm --cached <filename>: Removes the file from Git's index (staging area) but leaves the file on your local disk.
  • git commit -m "message": Commits the change to stop tracking the file.
bash
git rm --cached <filename>
git commit -m "Stop tracking <filename>"
💻

Example

This example shows how to stop tracking a file named secret.txt but keep it on your computer.

bash
git rm --cached secret.txt
git commit -m "Remove secret.txt from Git tracking"
Output
[master 1a2b3c4] Remove secret.txt from Git tracking 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 secret.txt
⚠️

Common Pitfalls

Common mistakes when removing files from Git but keeping them locally:

  • Using git rm <filename> without --cached deletes the file from both Git and your local disk.
  • Not committing after git rm --cached means the change is not saved in Git history.
  • Forgetting to add the file to .gitignore if you want Git to ignore it in the future.
bash
Wrong way (deletes file locally):
git rm secret.txt

Right way (keeps file locally):
git rm --cached secret.txt
📊

Quick Reference

Summary tips for removing a file from Git but keeping it locally:

  • Use git rm --cached <filename> to untrack the file.
  • Commit the change to update Git history.
  • Add the file to .gitignore to prevent future tracking.

Key Takeaways

Use git rm --cached <filename> to stop tracking a file but keep it locally.
Always commit after removing a file from Git tracking to save the change.
Add files to .gitignore to prevent Git from tracking them again.
Avoid using git rm <filename> without --cached if you want to keep the file locally.