Use Multiple Github Users on One Computer

Say you have multiple github account, and want to use different account to work on different repo, here is how you can do that.


TL;DR.

  1. Config SSH host alias
  2. Clone repo through SSH using one of the host alias instead of github.com

Detail Steps

Generate SSH keys for each of the github user

See Generating SSH keys (github)

$ cd ~/.ssh
$ ssh-keygen -t rsa -b 4096 -C "user1@example.com"
$ ssh-keygen -t rsa -b 4096 -C "user2@example.com"

When prompt the file name, provide different names for different keys. Don’t use default name since you want something easier to remember.

In above case, what you want to get is something like:

id_rsa_github_user1
id_rsa_github_user2

Add SSH keys

$ ssh-add -D  # this will delete all cached keys
$ ssh-add id_rsa_github_user1
$ ssh-add id_rsa_github_user2

Modify SSH Config to Enable Aliases

$ cd ~/.ssh
$ vi config

Then add following to the config file

# user1 SSH alias
Host github-user1
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_github_user1

# user2 SSH alias
Host github-user2
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_github_user2

And then add those SSH keys to local ssh-agent so that next time if you clone the github repo, the correct key will be used.

Add generated SSH keys to different github account

See STEP 4 of Generating SSH keys (github)

For user1:

Copy the key into clipboard:

$ pbcopy < ~/.ssh/id_rsa_github_user1.pub

Then go to github UI, login with user1, and paste the SSH key.

Do the similar thing for user2.

Clone Repo through SSH

$ git clone git@github-user1:<github-client1>/<repo1>.git
$ git clone git@github-user2:<github-client2>/<repo2>.git

Now if you are in <repo1> folder and do git push, it will use the SSH credential from id_rsa_github_user1. Similar to <repo2> in which case it will use id_rsa_github_user2 automatically.

Bonus Step: Use keychain to automatically add SSH keys for each session

Install keychain using brew:

$ brew install keychain

Add following line into your .bash_profile (or .zshrc for zsh user):

eval `keychain — eval — agents ssh — inherit any id_rsa_github_user1 id_rsa_github_user2`

Now you only need to provide the passcode for each of the SSH key once after the machine starts. After that if you open new terminal sessions, you will see the keychain adds the keys for you automatically:

* keychain 2.8.1 ~ http://www.funtoo.org
* Inheriting ssh-agent (forwarded)
* Known ssh key: /Users/yourloginname/.ssh/id_rsa_github_user1
* Known ssh key: /Users/yourloginname/.ssh/id_rsa_github_user2

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.