Skip to content

Instantly share code, notes, and snippets.

@nejads
Created August 25, 2021 16:34
Show Gist options
  • Save nejads/4f38b6a81163469847361e2aa7cb0dea to your computer and use it in GitHub Desktop.
Save nejads/4f38b6a81163469847361e2aa7cb0dea to your computer and use it in GitHub Desktop.
How to setup multiple ssh key for different git accounts

Setup multiple SSH keys

Create different keypairs

Create different ssh keys according to the Github documentation

ssh-keygen -t rsa -C "your_email@youremail.com"

For example, 2 keys were created at

~/.ssh/personal-on-mac
~/.ssh/work-on-mac

Modify the ssh config

Create/modify the ssh config file

vim ~/.ssh/config

Then add

# Personal account
Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/personal-on-mac

# Work account
Host git.work.com
  HostName git.work.com
  User #####
  IdentityFile ~/.ssh/work-on-mac

Add/Remove keys to/from OpenSSH agent

Start the ssh-agent

eval "$(ssh-agent -s)"

To be sure which domain (personal, work or...) you are working on, you can all the existing keys which are cached and add the corresponding private key to the OpenSSH authentication agent:

ssh-add -D
ssh-add ~/.ssh/work-on-mac

The bash functions can help you to switch between accounts smoothly

function personal-git() {
  ssh-add -D
  ssh-add ~/.ssh/personal-on-mac
   echo "You are using your PERSONAL ssh key"
}

function work-git() {
  ssh-add -D
  ssh-add ~/.ssh/work-on-mac
   echo "You are using your WORK key"
}

Switch Git profile

If you find it annoying to change your email in the .gitconfig file each time you want to switch between personal and work git, you can use conditional git configuration based on where your repositories are located on your machine. Let's imagine all your work-related repositories are in ~/workspace/ then you can configure ~/.gitconfig like following

// ~/.gitconfig
[user]
  name = Jane doe
  email = jane@doe.com

[includeIf "gitdir:~/workspace/"]
  path = ~/workspace/.gitconfig

And in the ~/workspace/.gitconfigput your work email so it overrides the default values

// ~/workspace/.gitconfig[user]  email = jane@work.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment