Setup multiple git ssh accounts for git

  1. Generate SSH keys
ssh-keygen -q -t rsa -C "john.smith@github.com" -f ~/.ssh/id_rsa -N ""
ssh-keygen -q -t rsa -C "john.smith@company.com" -f ~/.ssh/id_rsa_pro -N ""
  1. Link them with GitHub/Bitbucket, or any other account
  2. Use following example to set each ssh key for every repository in your ~/.ssh/config file You can configure ssh to send a use of a specific encryption key depending on the host. By this configuration, we can achieve of having multiple aliases for the same hostname.
Host github.com
 HostName github.com
 User git
 IdentityFile ~/.ssh/id_rsa
 IdentitiesOnly=yes
Host gitlab.com
 Hostname gitlab.com
 User git
 IdentityFile ~/.ssh/id_rsa_pro
 IdentitiesOnly=yes
  1. Git remote configuration We can use these aliases in the git remotes by changing git@github.com to git@github_pro.

Another option is to change existing projects remotes to something like git remote set-url origin git@github_pro:foo/bar.git or adapt them directly during cloning

git clone git@github.com:johnsmith/example.git
git clone git@github_pro:johnsmith/example.git

Set multiple git identities

  1. In your home directory create separate directories for your private and work repositories
$ mkdir private && mkdir work

# Used for personal repositories
$ ls private

# Used for work repositories
$ ls work
  1. Remove the [user] block in your ~/.gitconfig file and add the following
[includeIf "gitdir:~/private/"]
  path = .gitconfig-private
[includeIf "gitdir:~/work/"]
  path = .gitconfig-work
  1. In ~/.gitconfig-private add your personal user information
[user]
  email = john.smith@github.com
  name = John Smith
  1. In ~/.gitconfig-work add your work user information
[user]
  email = john.smith@company.com
  name = John Smith

Test setup

Note: includeIf works only in repositories under ~/private/ or ~/work/ and not in a non-repo directory.

Check if your settings were taken into account for instance in ~/private/<repository>

$ cd ~/private/<repository>
$ git config --get user.name
$ git config --get user.email

You can also display and check the global git config

$ git config --list --global

Or just the local config for the repository folder you are in

$ git config --list