Skip to content

Instantly share code, notes, and snippets.

@pbatey
Last active September 11, 2022 23:24
Show Gist options
  • Save pbatey/ddbe861d2c97a5275debd8be46a17742 to your computer and use it in GitHub Desktop.
Save pbatey/ddbe861d2c97a5275debd8be46a17742 to your computer and use it in GitHub Desktop.
Two git accounts

Two Github Accounts

My workplace has recently begun using github-enterprise hosted by github in the cloud, rather than using github-enterprise in a self-hosted environment. This means that I now have another account tied to my company user-identity which conflicted with my git ssh configuration.

I wasn't thrilled with the other solutions I'd found to manage two accounts:

  • Shell script wrappers around git that set the SSH_COMMAND environemnt varialbe on the fly, and
  • Changing the origin in the repo's .git/config to use a fake hostname (github.com-personal) and map the fake hostname in ~/.ssh/config.

But, today I found a solution that works entirely within git config definitions!

This method allows git to determine the ssh identity based on where the local repo is located. It did require me to move my cloned repos to either ~/src/personal or ~/src/work. I used to have them all user ~/src/github.com/ (might just be a me thing 😊).

~/.gitconfig:

# default account is my personal account
[user]
  email = pbatey@gmail.com
  name = Phil Batey
[github]
  user = pbatey
[core]
  sshCommand = ssh -i ~/.ssh/id_ed25519

# determine account by sub-directory
[includeIf "gitdir:~/src/work/"]
  path = ~/.gitconfig.work
[includeIf "gitdir:~/src/personal/"]
  path = ~/.gitconfig.personal

# settings that apply to all
[difftool "sourcetree"]
  cmd = opendiff \"$LOCAL\" \"$REMOTE\"
[mergetool "sourcetree"]
  md = /Applications/Sourcetree.app/Contents/Resources/opendiff-w.sh \"$LOCAL\" \"$REMOTE\" -ancestor \"$BASE\" -merge \"$MERGED\"
  rustExitCode = true
[color]
  ui = true
[push]
  default = simple
[init]
  defaultBranch = main
[status]
  submoduleSummary = true
[pull]
  rebase = true

~/.gitconfig.work:

[user]
  email = philip_batey@comcast.com
  name = Phil Batey
[github]
  user = pbatey200
[core]
  sshCommand = ssh -i ~/.ssh/id_ed25519_pbatey200_comcast

~/.gitconfig.personal:

[user]
  email = pbatey@gmail.com
  name = Phil Batey
[github]
  user = pbatey
[core]
  sshCommand = ssh -i ~/.ssh/id_ed25519

Then make sure you don't have github.com defined as a Host in ~/.ssh/config with IdentitiesOnly=yes (I did and it broke the sshCommand definition). I now just have my default ssh identity defined in ~/.ssh/config and keep all my github identity definitions in ~/.gitconfig.

Host *
 AddKeysToAgent yes
 UseKeychain yes
 IdentityFile ~/.ssh/id_rsa

This is the solution I was most happy with, I hope this information helps you too!

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