Herding Gits

August 26, 2021  |  2 minutes to read


Juggling multiple Git identities can be tricky.

A screenshot of the Git logo

For example, at Stripe, we encourage developers to create a separate GitHub account for Stripe-related open source activity. For me, this means I now own both a nfriend and a nfriend-stripe GitHub profile.

While setting up my dev environment, I had a few goals:

  • Use both Git identities on the same machine
  • Sign commits with separate GPG keys
  • Connect to remotes using different SSH keys
  • Have all of this 👆 happen automatically without me having to think about it

Good news! This is possible with a little .gitconfig magic ✨

The setup

Note: The instructions below rely on Git’s conditional includes, which are only available in Git 2.13 and beyond.

1. Set up separate SSH and GPG keys for each identity

I won’t go into details since this is already covered in great detail by other tutorials. GitHub’s tutorials are particularly well-presented:

2. Create separate directories for each identity

For example, a ~/github-personal and a ~/github-work directory.

3. Create a .gitconfig_include file in each

Inside each of these new directories, create a new file named .gitconfig_include with the following content:

[user]
  name = Your Name
  email = your-name@example.com
  signingkey = 0123456789ABCDEF

[core]
  sshCommand = ssh -i ~/.ssh/id_rsa_example -F /dev/null

Update each file with the name, email, and signing key for the corresponding Git identity.

Additionally, update the command in the sshCommand option to reference the appropriate key file.

4. Reference these files from the global .gitconfig

In your global .gitconfig (i.e. ~/.gitconfig), configure Git to conditionally include the correct .gitconfig_include file based on the current directory:

[includeIf "gitdir:~/github-personal/"]
  path = ~/github-personal/.gitconfig_include

[includeIf "gitdir:~/github-work/"]
  path = ~/github-work/.gitconfig_include

5. Test it!

Create a test project with both identities. Ensure you can:

  1. Clone the repository from the remote
  2. Make a commit
  3. Push the commit to the remote

If you’re using a web UI like GitLab or GitHub, check to see that your commits are being signed correctly and are labeled as “Verified”:

A screenshot of GitLab showing a 'Verified' label next to a commit


Some things I found helpful while setting this up:

Feedback

Thoughts? Let me know in this GitLab issue!


Other posts you may enjoy:

GitLab Pages with multiple domains

October 14, 2024  |  3 minutes to read

Zoom light

May 31, 2024  |  6 minutes to read

I built a weird keyboard

June 26, 2023  |  14 minutes to read

Wordle Bot

January 25, 2022  |  6 minutes to read

It's finally here! 🎉

May 7, 2021  |  1 minute to read