Working with multiple git email addresses
In this post, we’ll explore how to configure Git to use different usernames based on the directory you’re working in. This can be useful when working on multiple projects with different email addresses associated with each one. eg personal projects, work projects, client projects, etc.
Lets assume a folder structure like this:
~/code/
├── personal/
│ └── project1/
│ └── project2/
├── company/
│ └── project1/
│ └── project2/
├── client1/
│ └── project1/
│ └── project2/
├── client2/
│ └── project1/
│ └── project2/
The .gitconfig
is where we can configure git git username
and email
settings. However this file is either in each repository or in the global git configuration.
Ideally we would like to have a different email address for each of the directories in the ~/code/
folder.
However there is a way to achieve this using the includeIf
directive in the global .gitconfig
file.
[includeIf "gitdir:~/code/personal/"]
path = .gitconfig-personal
[includeIf "gitdir:~/code/work/"]
path = .gitconfig-work
[includeIf "gitdir:~/code/client1/"]
path = .gitconfig-client1
[includeIf "gitdir:~/code/client2/"]
path = .gitconfig-client2
In this configuration, you would have four separate .gitconfig
files:
~/code/personal/.gitconfig-personal
,~/code/work/.gitconfig-work
,~/code/client1/.gitconfig-client1
,~/code/client2/.gitconfig-client2.
Each of these files would contain the user email configuration for the respective directory.
For example, the .gitconfig-personal
file might look like this:
[user]
email = personal-email@domain.com
To validate that your configuration is working as expected, you can use the git config user.email
command in the terminal while inside the repository directory. This command will display the email address that Git is currently configured to use for that repository. If the output matches the email address you specified in the .gitconfig file for that directory, then you've successfully configured Git to use different author email addresses based on the repository location.
Happy coding!