How to Use Per-Directory Git Configs with `includeIf`
Sometimes you need different Git configurations for different repositories.
Real-Life Case: On your company laptop, you have your personal dotfiles repository where you use your personal email. However, for all company repositories, you want to use your work email or other corporate-specific configurations.
Solution
The includeIf directive in your global Git configuration file ~/.gitconfig allows you to specify a path prefix condition. When the condition is met, Git loads a separate configuration file.
~/.gitconfig
[user]
name = John Smith
email = john@smith.com
[includeIf "gitdir:~/git/work/projects/"]
path = ~/.gitconfig-for-work
~/.gitconfig-for-work
[user]
name = jsmith
email = jsmith@acme.com
How it works:
- The main
.gitconfigfile sets your personal name and email - The
includeIfdirective checks if the Git directory (gitdir) starts with the specified path (~/git/work/projects/) - If the condition is true, Git also loads the configurations from
~/.gitconfig-work, overriding the user name and email with your work-specific values