How to Manage Multiple SSH Keys and Git Accounts
Setup SSH Keys
Let’s assume your two git accounts are names gitPersonal and gitWork respectively.
Create two SSH keys, saving each to a separate file:
ssh-keygen -t rsa -C "namePersonal@personal.com
# save it as id_rsa_personal when prompted
ssh-keygen -t rsa -C "nameWork@work.com
# save it as id_rsa_work when promptedThe above commands setup the following files in ~/.ssh folder:
- id_rsa_personal
- id_rsa_personal.pub
- id_rsa_work
- id_rsa_work.pub
Add the keys to you git accounts
For example to add the key in GitHub, you should
- Go to your Account Settings
- Click
SSH keysthenAdd SSH key - Paste your key into the
Keyfield and add a relevant title - Click
Add keythen anter your GitHub password to confirm
Repeat the process for both gitPersonal and gitWork accounts.
Create a configuration file to manage the separate keys
Create and edit a config file in ~/.ssh
vim configAdd these lines to the config file and save it.
# gitPersonal
Host personal
HostName github.com # or bitbucket.org
User git
IdentityFile ~/.ssh/id_rsa_personal# gitWork
Host work
HostName github.com # or bitbucket.org
User git
IdentityFile ~/.ssh/id_rsa_work
Update stored identities
Clear currently stored identities:
ssh-add -DAdd new keys:
ssh-add id_rsa_personal
ssh-add id_rsa_workTest to make sure server recognizes the keys:
ssh -T personal
ssh -T workUpdate repo remote URLs
For personal repositories set remote URLs to:
git remote set-url origin git@personal:USERNAME/REPOSITORY.gitAnd setup the user.name and user.email for your personal account:
git config user.name "Personal Name"
git config user.email "namePersonal@personal.com"For work repositories set remote URLs to:
git remote set-url origin git@work:USERNAME/REPOSITORY.gitAnd setup the user.name and user.email for your work account:
git config user.name "Work Name"
git config user.email "nameWork@work.com"Notice how we used the custom accounts personal and work instead of github.com # bitbucket.com.
