How to stop tracking a file in Git?
When working on a Git repository, a developer may want to stop tracking the changes of a file. Luckily this is very easy to do in Git.
To stop tracking a file in Git and KEEP it in the repo, use:
git rm file.txt --cached
To stop tracking a file in Git and REMOVE it from the repo, use:
git rm file.txt
This article will explore different scenarios when stopping the tracking of a file in Git and answer common questions.
Let’s get to it.
How to stop tracking a file without deleting it?
You need to use the git rm command with the cached
option to stop tracking a file without deleting it.
The cached
option removes the file from the index but keeps it in the working directory.
Here is the process to follow:
- Remove the file from the index.
git rm file.txt --cached
2. Use the git status command to verify the changes.
3. Commit your changes.
git commit -m 'Removed the file'
4. Push your changes to the remote.
Note: You can remove a folder using the recursive option with git rm -r
.
How to stop tracking a file and remove it from the repo?
Using the git rm command, you can stop tracking a file without keeping it inside the repo.
Here is the process to follow:
- Remove the file.
git rm file.txt
2. Commit and push your changes to finalize the removal.
How to stop tracking a file but still keep it in the repo?
Sometimes, a developer may want to keep the file in the Git repository but stop tracking its changes.
That is where the git update-index
command with the skip-worktree
option comes into play.
The skip-worktree
option tells Git to pretend that the file is always up-to-date, so the changes are not tracked.
Here is the process to follow:
- Update the Git index.
git update-index --skip-worktree file.txt
The tracking is now off on the file called file.txt
.
Final thoughts
As you can see, it is easy to stop tracking the changes of a file in Git.
For a new file, however, include it in the .gitignore
file (if you want Git not to track it).
Here are some other Git tutorials for you to enjoy: