Managing Multiple GitHub Accounts Using SSH Keys on a Single Machine
Managing multiple GitHub accounts on a single machine can sometimes be a necessity for developers, freelancers, and professionals who work on multiple projects or collaborate across different organisations. However, handling multiple accounts seamlessly can become cumbersome without proper organisation and setup. One common challenge is managing authentication and access control for each account, especially when using SSH keys for secure communication with GitHub repositories.
In this guide, we’ll discuss how to set up SSH keys for each GitHub account, configure SSH and Git to use the correct keys for different repositories, and handle authentication challenges.
First let’s generate the ssh keys for both account
Open terminal and type these commands:
cd ~/.ssh
ssh-keygen -t rsa -C "first_email@email.com" -f "github-identifier1"
The above command will ask for passphrase, you can enter a passphrase or leave it empty.
Do same for the second identifier
ssh-keygen -t rsa -C "second_email@email.com" -f "github-identifier2"
“identifier1” and “identifier2” can be anything as far it’s unique.
Now let’s add the SSH keys to SSH-agent
ssh-add -K ~/.ssh/github-identifier1
ssh-add -K ~/.ssh/github-identifier2
You should see “Identity added…” for both.
Then we add the keys to the respective Github accounts
First, copy the ssh-key for “github-identifier1”, this command will copy the ssh-key to your clipboard.
pbcopy < ~/.ssh/github-identifier1.pub
Adding the ssh-key to GitHub
- Go to the Github account you want to link identifier1 with,
- under Settings => SSH and GPG keys => New SSH key.
- Paste the key, enter any title for the key and click on Add SSH Key
Repeat above steps to link identifier2 with another Github account
Create config file
Now we need to create a config file by running these commands:
touch ~/.ssh/config
open -e ~/.ssh/config
Paste the following and make changes to match your identifiers and save the config file.
#identifier1
Host github.com-identifier1
HostName github.com
User git
IdentityFile ~/.ssh/identifier1-github
#identifier2
Host github.com-identifier2
HostName github.com
User git
IdentityFile ~/.ssh/identifier2-github
Let’s make one of the account our default global account
git config --global user.name "username"
git config --global user.email "email@domain.com"
Cloning repo with the ssh-key
To clone any repository, you need to use the ssh url of the repo.
git clone git@github.com-{identifier}:{username-of-owner}/{repo-name}.git
Say for example we want to clone the flutter repo using “identifier1”
git clone git@github.com-identifier1:flutter/flutter.git
We can set the local configuration for username and email using
git config user.name "username for identifier1"
git config user.email "email for identifier1"