Stop tracking changes to certain files in Git

If you’ve used git before, you’re probably aware of the .gitignore file. This is what the manual has to say:

A gitignore file specifies intentionally untracked files that Git should ignore.

This file is usually tracked in your Git repo, so every contributor ignores the same files. Interestingly, you can also have a global ignore file in your home directory too ~/.gitignore. I have a global ignore file for ignoring basic IDE files.

Recently, I had a situation whereby the team was split on whether a file should, or should not, be ignored. Tricky, however, there is a way around it.

Assume unchanged

Let’s say a file is not going to be ignored in the repo, but you specifically don’t want to track changes to this file locally, you can run the following command.

git update-index --assume-unchanged [file]
Enter fullscreen mode
Exit fullscreen mode

This is what the manual has to say:

When this flag is specified, the object names recorded for the paths are not updated. Instead, this option sets/unsets the “assume unchanged” bit for the paths. When the “assume unchanged” bit is on, the user promises not to change the file and allows Git to assume that the working tree file matches what is recorded in the index.

OK, so you’re promising that you won’t change the file. I think this works for our situation, as the promise is really “I don’t mind if Git doesn’t track this file locally”. This does not impact anyone else on your project either, so it’s win win.

OK, let’s say you change your mind and you do want to commit changes to the file. Here’s what you do to track the file locally again.

git update-index --no-assume-unchanged [file]
Enter fullscreen mode
Exit fullscreen mode

What if you’ve completely forgotten what files you are, or are not, assuming unchanged?

git ls-files -v | grep "^[[:lower:]]"
Enter fullscreen mode
Exit fullscreen mode

The -v flag will alter the ls-files output to put a lowercase letter before the file if the assume-unchanged bit is set. e.g.

h untracked-file.ts
H tracked-file.ts
Enter fullscreen mode
Exit fullscreen mode

This means we can then grep on lowercase letters to see which files are assume-unchanged.

Summary

Hopefully, this solution helps you ignore files that you don’t want to commit by accident, without them being in the .gitignore file for your project.


See also


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top