Ken Muse

Creating a .gitignore Without Committing


This is a post in the series Configuring Git. The posts in this series include:

For most projects, we store a .gitignore file that indicates files and folders which should not be tracked by Git. This keeps those files out of our source control. For example, if we’re working with .NET, we don’t usually want the compiled binaries in bin or the intermediate files in obj to be included. The configurations are surprisingly consistent. In fact, becaus of this the community has been curating them by platform.

Unfortunately, we can’t always have nice things. Sometimes, there are reasons why we can’t utilize a .gitignore in the repository. This may be caused by an owner that forgot to include the file or the use of historical repositories. Occasionally, it’s bad practices that we can’t easily avoid. How can we better handle these situations? The trick is to understand the ways that Git determines which files to ignore.

By default, Git looks for a global definition that applies to all repositories. This path is configurable (using the configuration parameter core.excludesFile). If it is not configured, it defaults to $XDG_CONFIG_HOME/git/ignore. The global environment variable XDG_CONFIG_HOME exists in some Linux variants, but not all. As a fallback, $HOME/.config/git/ignore is used if XDG_CONFIG_HOME is not configured. This works for most Linux variants and MacOS. For Windows, the path should be configured manually by configuring core.excludesFile:

1git config --global core.excludesFile "%USERPROFILE%\.gitignore"

For PowerShell, you can use $Env to read the profile path:

1git config --global core.excludesFile "$Env:USERPROFILE\.gitignore"

This works great for global files, but sometimes we want to alter the current repository’s behavior. To do this, we have to understand that the local repository has some special file paths. These files configure the local repository, but are not pushed to the remote. That allows you to customize the behavior of a local repository. One of these is .git/info/exclude. If the exclude file exists, it can be used just like a .gitignore file in the root of the repository. It is not committed or shared with other developers, so it provides a way to prevent files from being tracked only in the current environment.

Obviously, it’s best when you can use a .gitignore, but sometimes it’s nice to know you have global and local options. While it’s not something most people will need, Git provides you with the choices. After all, the developer knows best, right? 😄