Most of the time I don’t have any issues with git’s
.gitignore system but occasionally it doesn’t behave as I expect. Usually, I add and remove lines until I get the result I’m after and leave feeling vaguely unsatisfied with myself. I always had a nagging feeling that there must be a smarter way to do this, but I was never able to find it. Until today!
git check-ignore. You pass it files on the command line, and it tells you if they’re ignored or not, and why. Sounds pretty perfect right? I won’t give you a run down of all the options, as the man page is surprisingly readable (especially for a git man page!). However the 30-second version is
git check-ignore --verbose --non-matching <filepath to check>:
$ echo "b" > .gitignore $ # a is a file that would be matched $ git check-ignore --verbose --non-matching a :: a $ # b is a file that would be ignored $ git check-ignore --verbose --non-matching b .gitignore:1:b b
--verbose prints the explanation of why a file was ignored.
--non-matching makes sure the file is printed out, even if it won’t be ignored.
If a file is going to be ignored,
check-ignore prints out the path to the gitignore file and line that matched. Interestingly, the files don’t even need to exist, git just checks what it would do if they did exist.
check-ignore I was able to solve my problem faster, and learn a bit more about git’s arcane exclusion rules. Another handy tool to add to my unix utility belt.