Title: Conditional overriding of Git configurations for single and multiple repositories
Description: How to change configuration properties like your Git user when working in different contexts for no more accidental commits with the wrong name or email address.
Have you ever created or cloned a Git repository for work on your personal machine or vice-versa, and accidentally made a commit with the global Git email? It happens to the best of us.
In general, Git stores its configuration properties within the global configuration file
~/.gitconfig in your home directory. Sometimes you may want to change your configuration for specific projects/repositories, e.g. if you’re working within different contexts like private projects vs. work projects vs. university projects.
All you need to do is adding your intended configuration to
.git/config within the respective repository. For example, to change your name or email address for commits, simply add the following contents within that configuration file.
[user] name = John Doe email = firstname.lastname@example.org
(You can also simply run
git config user.name "John Doe" and
git config "user.email email@example.com" within the repository.)
.git/config is not part of the versioning (but actually its configuration—who would have thought), this change is only in place for your local repository clone.
However, if you’re having multiple affected repositories, this is quite time-consuming and has to be done for each and every repository individually. The good news: there is a more scalable way! Using Git’s conditional includes, you can override your global configuration for specific path patterns within
~/.gitconfig in your home directory.
# ~/.gitconfig [user] name = John Doe email = firstname.lastname@example.org [includeIf "gitdir:~/Repositories/work-*/"] path = ~/.gitconfig-work [includeIf "gitdir:~/University/Code/"] path = ~/.gitconfig-university
This tells Git to load the Git configuration file at
~/.gitconfig-work for all repositories within
~/Repositories starting with the prefix
~/.gitconfig-university is loaded for all repositories within the directory
~/University/Code. For every other repository, the global default configuration will be used.
The respective conditional configuration files could look like as follows.
# ~/.gitconfig-work [user] email = email@example.com
# ~/.gitconfig-university [user] name = John Michael Doe email = firstname.lastname@example.org
(Git also supports the keyword
gitdir/i instead of
gitdir which will match the provided pattern case-insensitively.)
You can verify whether your desired configuration is used by running
git config user.name or
git config user.email within your respective repository.