This gist outlines how to configure multiple SSH keys for different GitHub accounts on a single machine.
Generate two SSH key pairs, one for each GitHub account, ensuring you specify a unique file path for each. Replace the example emails with your actual emails.
$ ssh-keygen -t rsa -f ~/.ssh/id_rsa_work -C "[email protected]"
$ ssh-keygen -t rsa -f ~/.ssh/id_rsa -C "[email protected]"
This will create two key pairs:
- ~/.ssh/id_rsa_work (and its public key ~/.ssh/id_rsa_work.pub) for your work account.
- ~/.ssh/id_rsa (and its public key ~/.ssh/id_rsa.pub) for your personal account.
First, clear any existing keys from the agent:
$ ssh-add -D
Then, add your new keys:
$ ssh-add ~/.ssh/id_rsa_work
$ ssh-add ~/.ssh/id_rsa
Verify the keys are added:
$ ssh-add -l
Edit (or create) your SSH config file:
$ nano ~/.ssh/config
Add the following configuration, replacing placeholders with your actual GitHub username:
#Work GitHub account
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa
#Work GitHub account
Host github.com-work
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_work
Personal Repository:
Clone your personal repositories as usual:
$ git clone [email protected]:your_personal_username/repo_name.git
Work Repository:
Use the github.com-work hostname defined in your SSH config:
$ git clone [email protected]:your_work_username/repo_name.git
Global Config (for personal account):
$ git config --global user.name "Your Personal Name"
$ git config --global user.email "[email protected]"
Work Repository Specific Config:
Navigate to the work repository's directory:
$ cd project-name
Then set the user settings:
$ git config user.name "Your Work Name"
$ git config user.email "[email protected]"
You should now be able to push and pull to both your personal and work repositories without any SSH key conflicts. Remember to use the correct remote URL (github.com or github.com-work) depending on the repository.
Finally, add the contents of the public key files (~/.ssh/id_rsa.pub and ~/.ssh/id_rsa_work.pub) to your respective GitHub accounts under "Settings" -> "SSH and GPG keys". You can copy the contents of the public keys using
$ cat ~/.ssh/id_rsa.pub
$ cat ~/.ssh/id_rsa_work.pub.