How to untrack files after adding gitignore?

You can use git rm –cached command to untrack files and directories that are already being tracked after adding gitignore.

gitignore file is used to ignore any files or directories that you don’t want git to track. Once you add a gitingore file containing details on files or directories that you want git to ignore, git will not track any new file or directory. But existing files or directories that are already being tracked by git will not get ignored. In this case, you need to remove git cache to ignore existing tracked files or directories.

On the other hand, you might want git to track a file or directory that is included in your gitignore file, use git add -f option in such cases.

Example:

Create a new local git repository:

Create a change and commit to your local repository default branch:

Create a new file and directory and stage the changes:

Add a .gitignore file that excludes the new file directory from being tracked:

Check the git status:

Observe: Though we have added a gitignore file to explicitly untrack the new file and directory, git is still tracking them. This happened as the new file and directory were already being tracked by git when we added the gitignore file.

Untrack existing tracked files and directories in git:

Check git status: