Skip to content

How to Separate Git Configs Between Multiple Projects

Git/

When working on many projects that use Git for version control, it is not unusual to have the need to use a different name or email address per project. Most likely any work related project requires a work email, while personal email should be used otherwise.

Each Git repository can contain a local configuration file where work related configuration could be specified, but that can get tiresome quickly if you have to create the same configuration for every new project.

The solution is to conditionally include a separate config for any time you work on a work related project into the global config using includeIf statement.

Creating a Conditional Config

To achieve the desired result of including a config within another, take the following steps.

  1. Have the work projects organized under a common directory. For example ~/Projects/Work

    mkdir -p ~/Projects/Work
    
  2. Create a .gitconfig file in ~/Projects/Work and add the configuration to be used for every work project

    [user]
            name = John Doe
            email = [email protected]
    
  3. Adjust the global configuration, which is usually located in ~/.gitconfig, to include the includeIf statement

    [user]
            name = hackerman
            email = [email protected]
    
    [includeIf "gitdir:~/Projects/Work/"]
            path = ~/Projects/Work/.gitconfig
    

    This does two things. Whenever Git is used, it checks if the command is ran from a Git repository under ~/Projects/Work directory. If that is the case, the ~/Projects/Work/.gitconfig file gets appended to the global Git configuration.

Checking The Configuration

The git config -l command can be used to see the global Git configuration.

git config -l

Which produces the following result if ran outside the ~/Projects/Work path.

user.name=hackerman
user.email=[email protected]
includeif.gitdir:~/Projects/Work/.path=~/Projects/Work/.gitconfig

Navigate to a work project repository and repeat the same command.

cd ~/Projects/Work/work-project
git config -l

This time, the configuration includes two entries for both the user.name and user.email. The configuration for work projects comes second, therefore it overrides the global configuration. Whenever a commit is made in any work project repository, the work name and email is used.

user.name=hackerman
user.email=[email protected]
includeif.gitdir:~/Projects/Work/.path=~/Projects/Work/.gitconfig
user.name=John Doe
user.email=[email protected]

Additional output, which comes from the local per project configuration in .git/config, has been removed from the example above.

References