Multiple identities with git
Let’s say you have a computer that you use for commiting changes to private, public and work repositories with git. Every time you enter that git commit
command you have to think: do I use the correct .gitconfig
now? Not any more!
⚠ Note that the
.gitconfig
-files should be saved in your home directory.
Let’s say that I want to default on my name Tyrell Wellick and the email adress tyrell@gcompany.com . I make my .gitconfig
file look like this:
[user]
name = Tyrell Wellick
email = tyrell@gcompany.com
So far, so good. At my work we have a git server that I reach with the address ssh://git@git.ecorp.com:9999/reponame/ . When I commit to that server I want to use my corporate address tyrell@ecorp.com and also I want to sign my commits with GPG. Let’s create a .gitconfig-ecorp
file with the following configuration:
[user]
name = Tyrell Wellick
email = tyrell@ecorp.com
sigingkey = 0123456789ABCDEF
[commit]
gpgsign = true
Ok, first of all. To find your signing key ID you use the gpg
command. You can also skip the signingkey
and commit/gpgsign
parts in the example above if you don’t want to use GPG signing for your commits.
$ gpg --list-secret-keys --keyid-format LONG tyrell@ecorp.com
sec ed25519/0123456789ABCDEF 2022-09-12 [SC] [expires: 2027-09-11]
9A3D92E4685D4B58C64049740123456789ABCDEF
uid [ultimate] Tyrell Wellick <tyrell@ecorp.com>
ssb cv25519/FEDCBA9876543210 2022-09-12 [E] [expires: 2027-09-11]
Your signing key ID is on the second row, in my example above you’ll see 0123456789ABCDEF as an example.
So now we have edited and saved the .gitconfig-ecorp
file and want to conditionally include that file if we are working with the git.ecorp.com git server. Let’s open the .gitconfig
file again:
[user]
name = Tyrell Wellick
email = tyrell@gcompany.com
In that file we add the following:
[user]
name = Tyrell Wellick
email = tyrell@gcompany.com
[includeIf "hasconfig:remote.*.url:ssh://git@git.ecorp.com:9999/**"]
path = ~/.gitconfig-ecorp
That’s it. Now git will take care of your identity and use the default (tyrell@gcompany.com) if you are git commiting to a repo, but if you are working with a repo from git.ecorp.com-git repo server you’ll get the identity of tyrell@ecorp.com .
Oh, if you wonder how you are GPG-signing a git commit. Add -S
to the git commit
command, like this: git commit -S
.
Versions used in this article
$ cat /etc/redhat-release ; git --version ; rpm -q git-core
Fedora release 38 (Thirty Eight)
git version 2.41.0
git-core-2.41.0-1.fc38.x86_64