Should I commit .gitignore files and other Git-ignoring issues

This text is a summary of my “Should I commit .gitignore file” question, and a few others (not mine), asked at Stack Overflow. It gathers all the useful answers, comments and facts about ignoring files and folders in Git. This is presented as quick-review checklist.

Key facts about ingoring files and folders in Git:

  1. You don’t have to commit (track) .gitignore files. You can do this only to share “general ignoring scheme” among other developers.
  2. All contents of .gitignore (all rules) take effect as soon as the file is created or modified.
  3. All ignoring rules affects untracked files only. If you want to ignore file, that was already commited, the file must be un-tracked (for example with git rm --cached filename).
  4. You can use special .git/info/exclude file (which uses the same format as .gitignore) to list all the ignores, that you don’t want to share with others (e.g. specific configuration files for an IDE, that only you use). Since this is a special checkout-local file, stored in in the .git folder, it never shows up in git status.
  5. If you want to remove all the ignored files, run git clean -f -X. Keep in mind, that there is no going back (since removed files are not tracked!), so “preview” the possible damage, you can do with this command, by adding --dry-run switch to it.

BTW: A comment to an answer about last point on above list, saying: “Prevent sudden cardiac arrest with -n“, by faraz, is my best ever, top favorite comment in entire Stack Exchange network!

The most important “myth”, that we should take care here, is (wrong!) assumption:

Uncommited .gitignore files’ rules doesn’t work and commiting them, is required for them to work.

This incorrect claim is repeated by many developers and Git users. That assumption is not true, as you can see from above and from linked SO question.

One more thing. Since Git cannot track a completely empty directory you have to place anything inside such. There are many solutions for this.

Some propose to put a README file with explanation, why completely empty directory is necessary in the project. Other replies, that in most cases such empty directory’s name is self-explanatory (i.e. assets, runtime) and no README file is ever needed.

The .gitignore file can help in this case as well — .gitignore file with two lines: * and !.gitignore is more than enough clarity. If this is not enough, you can put additional comment in the .gitignore file itself, using # character.

Of course, there is also a short’n’fine article at GitHub Help for people hunger for more! :]

Leave a Reply