0
0
GitHow-ToBeginner · 3 min read

How to Stop Tracking a File in Git: Simple Commands

To stop tracking a file in Git, use git rm --cached <file> to remove it from tracking without deleting it locally. Then, add the file to .gitignore to prevent Git from tracking it again.
📐

Syntax

The main command to stop tracking a file is git rm --cached <file>. Here:

  • git rm removes files from the staging area and working directory by default.
  • --cached tells Git to remove the file only from tracking (index), keeping it in your local folder.
  • <file> is the path to the file you want to stop tracking.

After this, add the file path to .gitignore to avoid tracking it in the future.

bash
git rm --cached <file>
💻

Example

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

bash
echo "This is a secret" > secret.txt

# Add and commit the file first
git add secret.txt
git commit -m "Add secret.txt"

# Stop tracking secret.txt without deleting it locally
git rm --cached secret.txt

# Add secret.txt to .gitignore to prevent future tracking
echo "secret.txt" >> .gitignore

# Commit the changes
git add .gitignore
git commit -m "Stop tracking secret.txt and ignore it"
Output
[master abc1234] Add secret.txt 1 file changed, 1 insertion(+) create mode 100644 secret.txt rm 'secret.txt' [master def5678] Stop tracking secret.txt and ignore it 2 files changed, 2 insertions(+) delete mode 100644 secret.txt
⚠️

Common Pitfalls

  • Using git rm <file> without --cached deletes the file from your local folder, which might be unwanted.
  • Not adding the file to .gitignore means Git will track it again if modified.
  • Changes to the file after stopping tracking won't be ignored unless .gitignore is updated.
bash
git rm secret.txt  # Wrong: deletes file locally

# Correct way:
git rm --cached secret.txt
# Then add to .gitignore
📊

Quick Reference

CommandPurpose
git rm --cached Stop tracking file but keep it locally
echo '' >> .gitignoreAdd file to ignore list
git add .gitignoreStage .gitignore changes
git commit -m 'message'Commit changes to repository

Key Takeaways

Use git rm --cached to stop tracking a file without deleting it locally.
Always add the file to .gitignore to prevent Git from tracking it again.
Avoid using git rm without --cached if you want to keep the file locally.
Commit your changes after removing tracking and updating .gitignore.
Stopping tracking does not delete the file from your computer.