← Today I Learned

Add a global .gitignore

If you use git on a Mac, chances are you’ve accidentally committed a .DS_Store to a repo. I used to reflexively add .DS_Store to all my .gitignore files to avoid ever repeating that mistake.

But there’s a better way! You can add a global .gitignore file to your global config with this command:

git config --global core.excludesFile '~/.gitignore'

The single quotes around ~/.gitignore aren’t strictly necessary; if you don’t use them, the ~ will just get expanded into the absolute path to your home directory.

Under the hood, that command just adds this to your ~/.gitconfig:

[core]
        excludesFile = ~/.gitignore

Update: You can now do this without modifying your ~/.gitconfig!! Not sure when this was added, but the git documentation now has this bullet point:

Patterns which a user wants Git to ignore in all situations (e.g., backup or temporary files generated by the user’s editor of choice) generally go into a file specified by core.excludesFile in the user’s ~/.gitconfig. Its default value is $XDG_CONFIG_HOME/git/ignore. If $XDG_CONFIG_HOME is either not set or empty, $HOME/.config/git/ignore is used instead.

Not sure what $XDG_CONFIG_HOME is, but it hasn’t been set on any systems computers I’ve used. On macOS and other Unix-like systems, the default is $HOME/.config/git/ignore, aka ~/.config/git/ignore. On Windows, that maps to %USERPROFILE%\config\git\ignore.