Skip to content

Instantly share code, notes, and snippets.

@valk
Forked from jexchan/multiple_ssh_setting.md
Last active January 3, 2022 14:10
Show Gist options
  • Save valk/3f01258491566db25673cbd28453d021 to your computer and use it in GitHub Desktop.
Save valk/3f01258491566db25673cbd28453d021 to your computer and use it in GitHub Desktop.
Multiple SSH keys for different github accounts

How to access multiple github accounts with different SSH Keys settings

Create different public keys

create different ssh keys according the article Mac Set-Up Git

$ ssh-keygen -t rsa -C "user1@example.com"
$ ssh-keygen -t rsa -C "user2@example.com"

Please refer to github ssh issues for common problems.

For example, 2 keys were created at:

~/.ssh/id_rsa_user1
~/.ssh/id_rsa_user2

Before adding users, you can check existing keys:

$ ssh-add -l

or delete all cached keys:

$ ssh-add -D

Then, add these two keys as following:

$ ssh-add ~/.ssh/id_rsa_user1
$ ssh-add ~/.ssh/id_rsa_user2

Finally, you can check your saved keys:

$ ssh-add -l

Modify the ssh config

$ cd ~/.ssh/
$ touch config
$ editor -a config   # use your favorite editor - vim, nano etc...

Then add:

#user1 account
Host github.com-user1
	HostName github.com
	User user1@example.com
	IdentityFile ~/.ssh/id_rsa_user1

#user2 account
Host github.com-user2
	HostName github.com
	User user2@example.com
	IdentityFile ~/.ssh/id_rsa_user2

Clone you repo if you haven't already

git clone git@github.com:user1/your_repo.git your_repo

Modify your Git config

cd your_repo and modify git config as needed, for example:

$ git config user.name "user2"
$ git config user.email "user2@example.com" 

Validate .git/config

editor .git/config

It should have this section:

[remote "origin"]
	url = git@github.com-user2:user2/your-repo.git
	fetch = +refs/heads/*:refs/remotes/origin/*

Make sure your url = part has the exact same syntax, note the -user2 in git@github.com-user2.

or you can have global git config $ git config --global user.name "user2" $ git config --global user.email "user2@example.com"

Like, share & profit!

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