Use Multiple Git Identities in the Same Environment

Use Multiple Git Identities in the Same Environment

I often (re-)use the same laptop to work in different projects that have to be committed to Github under different identities. By “identities” I do not mean different Github accounts. I sign my commits with SSH key registered at Github to emails that are associated with my Github account. Different types of projects are supposed to sign with different emails and keys. I could call git config... each time or maintain multiple .gitconfig files in different directories. However, there is more effective way IMHO. The way is to use includeif setting of the Git configuration. This is how it works.

First you will need to create SSH signing keys for each email that you want to use. Then to register them in your Github account. You can do it with GPG keys but I prefer to go with SSH and to use ED 25519 algorithm.

TIP: Be mindeful that if you want to ensure your keys cannot be used in different environments, you should create keys using passphrase. If you do not want to remember it, you can configure SSH agent to pass the phrase each time the key is used in your environment.

For the sake of example, let’s assume you sign your commits with email user1@domain1.com and use the key stored at ~/.ssh/id_ed25519_user1. And you want to use email user2@domain2.com and key ~/.ssh/id_ed25519_user1 when you work with specific folders.

Then all what you have to do is to set up signingkey and email in the [user] section of ~/.gitconfig to “default” values. Your ~/.gitconfig will look similar to below"

[user]
  name = <your Github account user>
  email = user1@domain1.com
  signingkey = ~/.ssh/id_ed25519_user1

#...
[commit]
  gpgsign = true

Create a standalone file with alternative settings, let’s call it .gitconfig.user2, with the following content:

[user]
  email = user2@domain2.com
  signingkey = ~/.ssh/id_ed25519_user2

Then to customize your main Git configuration (~/.gitconfig) file to use alternative identity in selected locations by adding one or more includeif statements AFTER the [user] block. The following statement configures Git to user “user2” email and signing key in ALL locations under ~/workdir/domain2_work/.

# after the [user] block add
[includeif "gitdir:~/workdir/domain2_work/"]
  path = "~/.gitconfig.user2"

Additionally to the gitdir you can condition your configuration to the branch or remote URI. Read includeif documentation to learn more.