How to Stop Tracking File in Git

Azhar Bashir Khan Feb 02, 2024
  1. Using git rm to Stop Tracking Files in Git
  2. Using git update-index to Stop Tracking Files in Git
How to Stop Tracking File in Git

In this tutorial, we will learn how to stop the tracking of files and folders in a repository in Git.

In a development repository, we often encounter a situation where we no longer want some files to be tracked for changes in Git.

Say we have a file that we feel is redundant now and no longer relevant to the project. In such cases, we want to remove the file from tracking in the repository in Git.

We will now illustrate this with an example.

Using git rm to Stop Tracking Files in Git

Suppose we have a file named file1 in the repository in Git, which we no longer wish to track.

We can remove the file from tracking in Git by using the git rm command with the --cached option.

$ git rm --cached file1
rm 'file1'

We can also remove a folder from tracking in the Git repository using the following command.

$ git rm -r --cached <folder-name>

This will remove the file or folder, as specified, from tracking (i.e.) remove it from the index; but will not delete the file from the filesystem.

Caution
When we do a git pull on other machines to get new changes from the remote repository, that file or folder will be removed from that filesystem. This will also cause the removal of the file or folder when we freshly clone from the remote repository.

Also, note that we need to commit the file removal to update this change in the remote repository.

$ git commit -m "Removed file1"
$ git push

Using git update-index to Stop Tracking Files in Git

Sometimes, we may wish to keep a file in the repository but no longer want to track its changes. We can use the git update-index command with the --skip-worktree option to achieve this.

$ git update-index --skip-worktree file1

The --skip-worktree option to command git update-index causes Git to pretend that the file’s version is up to date and instead read from the index version. This is especially useful for config files.

We may have some config files in the repository with default or production values, and we may make some changes to it as per our needs but don’t want to commit these changes. The --skip-worktree option to command git update-index is very handy for such purposes.

Thus, we have elaborated on stopping tracking files and folders in a Git repository.

Related Article - Git Tracking