Git config with multiple identities
Let’s say you work with multiple repositories, some personal, some work-related and you’re doing some freelance work for a friend or two. You definitely don’t want to use the same identity and expose your juicy don@fat.club
email and the linked GPG key you sign your commits with. Or if you’re bipolar.
Let’s assume your git config is similar to this (just an example, not the same name and email address, of course).
$ git config --get user.name
Don Donnington
$ git config --get user.email
don@fat.club
Start by removing the existing global identity:
# unset user name
$ git config --global --unset user.name
# unset user email
$ git config --global --unset user.email
# unset GPG signing key if you're using one, skip this line if it looks like voodoo magic to you
$ git config --global --unset user.signingkey
# require config to exist if you want to make commits
$ git config --global user.useConfigOnly true
Beginning with git version 2.13, you can use conditional includes that will help you configure everything correctly.
So, you need to set up a git username and email address depending on the directory you are in. Add the lines below in your ~/.gitconfig
:
# when you are in ~/projects the ~/.gitconfig-personal will be used
[includeIf "gitdir:~/projects/"]
path = ~/.gitconfig-personal
# when you are in ~/projects/work the ~/.gitconfig-work will be used
[includeIf "gitdir:~/projects/work/"]
path = ~/.gitconfig-work
# when you are in ~/projects/freelance the ~/.gitconfig-freelance will be used
[includeIf "gitdir:~/projects/freelance/"]
path = ~/.gitconfig-freelance
Add your personal information in the ~/.gitconfig-personal
file:
[user]
email = james.hetfield@somethingfancy.com
name = James Hetfield
signingkey = ACAB1234
Add your workplace information in the ~/.gitconfig-work
file:
[user]
email = jason.newsted@screwmetallica.eu
name = Jason Newsted
signingkey = FE2CCA41
[core]
sshCommand = ssh -i ~/.ssh/work_ed25519
Add your freelancing (if you need a third identity, of course) information in the ~/.gitconfig-freelance
file:
[user]
email = cliff.burton@rip.ie
name = Cliff Burton
signingkey = E1ADB1C9
If you want to test your configuration, move into one of the folders, for example ~/projects/work/
and check your git configuration:
$ cd ~/projects/work/
$ git config --get user.name
Jason Newsted
$ cd ~/projects/freelance/
$ git config --get user.name
Cliff Burton
Rock on!