How to Manage Multiple SSH Keys and Git Accounts

Gevorg A. Galstyan
Aug 22, 2017 · 2 min read

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 prompted

The 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 keys then Add SSH key
  • Paste your key into the Key field and add a relevant title
  • Click Add key then 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 config

Add 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 -D

Add new keys:

ssh-add id_rsa_personal
ssh-add id_rsa_work

Test to make sure server recognizes the keys:

ssh -T personal
ssh -T work

Update repo remote URLs

For personal repositories set remote URLs to:

git remote set-url origin git@personal:USERNAME/REPOSITORY.git

And 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.git

And 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.

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade