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
To achieve the desired result of including a config within another, take the following steps.
Have the work projects organized under a common directory. For example
mkdir -p ~/Projects/Work
~/Projects/Workand add the configuration to be used for every work project
[user] name = John Doe email = [email protected]
Adjust the global configuration, which is usually located in
~/.gitconfig, to include the
[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/Workdirectory. If that is the case, the
~/Projects/Work/.gitconfigfile gets appended to the global Git configuration.
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
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.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.