Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save qlawmarq/363b501fd4ff61dea75ace062f9b5884 to your computer and use it in GitHub Desktop.
Save qlawmarq/363b501fd4ff61dea75ace062f9b5884 to your computer and use it in GitHub Desktop.
How to switch between multiple GitHub accounts via ssh

How to switch between multiple GitHub accounts via ssh

Generate a new SSH key

Open Terminal, and create SSH keys for each accounts.

ssh-keygen -t ed25519 -C "your_email@example.com"

Please create different keys for each accounts.

> Enter a file in which to save the key (/Users/you/.ssh/id_ed25519): /Users/you/.ssh/id_ed25519
> Enter a file in which to save the key (/Users/you/.ssh/id_ed25519): /Users/you/.ssh/id_ed25519_sub

After that, SSH keys is generated in ~/.ssh/.

This type of key (~/.ssh/id_ed25519) is a secret key and should not be shared. Also, this type of key (~/.ssh/id_ed25519.pub) is a public key and you can share it to others.

ls ~/.ssh
id_ed25519	id_ed25519.pub

For more info: https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent

Remove SSH known_hosts (Optional)

If you have already connected to Github via SSH, delete known_hosts.

rm -rf ~/.ssh/known_hosts

Add public key to GitHub

Copy the public key to clipboard.

pbcopy < ~/.ssh/id_ed25519.pub

And add it to the following:

https://github.com/settings/keys

Repeat this for each account, using a different public key.

Create SSH config

If the config does not exist, create it.

touch ~/.ssh/config
vim ~/.ssh/config 

And, list configs for each accountm like so:

Host github-main
  HostName github.com
  IdentityFile ~/.ssh/id_ed25519
  IdentitiesOnly yes
  User git

Host github-sub
  HostName github.com
  IdentityFile ~/.ssh/id_ed25519_sub
  IdentitiesOnly yes
  User git

Connect SSH

Finally, make an SSH connection with different configs for each account.

ssh -T github-main
ssh -T github-sub

Make sure to use SSH instead of HTTPS, and also make sure to use the name you entered in the config.

BAD EXAMPLE ❌

git clone https://github.com/your_account/repo_name.git
git clone git@github.com:your_account/repo_name.git

CORRECT EXAMPLE ⭕️

git clone git@github-main:your_account/repo_name.git
git clone git@github-sub:your_account/repo_name.git
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment