Skip to content

Instantly share code, notes, and snippets.

@jamiebuilds
Last active May 14, 2024 09:49
Show Gist options
  • Save jamiebuilds/a0c4d20b738a3c31afe196640a967ea2 to your computer and use it in GitHub Desktop.
Save jamiebuilds/a0c4d20b738a3c31afe196640a967ea2 to your computer and use it in GitHub Desktop.

Multiple GitHub accounts (Work vs Personal)

This setup uses some tricks to ensure that the right email/name/ssh-key is used for the right repos without having to think about it ever again.

  • First generate two SSH keys, ~/.ssh/id_ed25519 and ~/.ssh/id_ed25519_work
  • Add one key to your personal account and the other to your work account

.ssh/config

# Personal SSH Key
Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519

# Work SSH Key: Rewrite `github.com-work` host to `github.com`
Host github.com-work
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519_work

Test with ssh -T git@github.com and ssh -T git@github.com-work

.gitconfig

# Personal Git Config
[user]
  email = you@example.me
  name = Yours Truly

# Assuming all your work repositories are in a single github org like `github.com/WORK_ORG`
# Conditionally include configs to override settings in those repositories
[includeIf "hasconfig:remote.*.url:git@github.com:WORK_ORG/**"]
  path = .gitconfig-work
  
# Rewrite `github.com:WORK_ORG` to `github.com-work:WORK_ORG` to get the right SSH key
[url "git@github.com-work:WORK_ORG/"]
	insteadOf = git@github.com:WORK_ORG/

Test by cloning a personal repo and a work repo using the SSH URL (git@github.com)

.gitconfig-work

# You can override any settings here you want for your work org
[user]
  email = you@example.biz
  name = Yours Truly

Test by running git config user.email in personal and work repositories

@nzjc
Copy link

nzjc commented Mar 15, 2024

One note I'll add is that if you use an ssh-agent, you'll wanna ssh-add both keys to that :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment