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 rmremoves files from the staging area and working directory by default.--cachedtells 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--cacheddeletes the file from your local folder, which might be unwanted. - Not adding the file to
.gitignoremeans Git will track it again if modified. - Changes to the file after stopping tracking won't be ignored unless
.gitignoreis updated.
bash
git rm secret.txt # Wrong: deletes file locally # Correct way: git rm --cached secret.txt # Then add to .gitignore
Quick Reference
| Command | Purpose |
|---|---|
| git rm --cached | Stop tracking file but keep it locally |
| echo ' | Add file to ignore list |
| git add .gitignore | Stage .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.