Use a specified key from ssh-agent

I finally got it to work:

Host USER1.git
  User git
  HostName github.com
  IdentityFile ~/.ssh/USER1.id_rsa

Host USER2.git
  User git
  HostName github.com
  IdentityFile ~/.ssh/USER2.id_rsa
  • Indentation counts.
  • Do ssh-add -l and make sure both of your keys have been added.
    • Copy/paste each path from ssh-add -l into the appropriate line in ~/.ssh/config to avoid typos. If there is a ~/.ssh/config identityfile path typo for USER1, then the wrong key (USER2's key) will be used instead.

I got the instructions over at BitBucket. They should work for GitHub since the only difference is HostName: http://confluence.atlassian.com/pages/viewpage.action?pageId=271943168#ConfiguringMultipleSSHIdentitiesforGitBashMacOSXLinux-CreateaSSHconfigfile

To get this to work on a remote server using agent forwarding, try @stijn-hoop's suggestion below (in the comments section of this answer).


The point is to use the public key file inside IdentityFile directive.

Host USER1.git
  User git
  HostName github.com
  IdentityFile ~/.ssh/USER1.id_rsa.pub

Host USER2.git
  User git
  HostName github.com
  IdentityFile ~/.ssh/USER2.id_rsa.pub

If we specify the private key inside the SSH config, SSH agent will fail to pick the right key if the private key is encrypted.

A similar question on stackexchange: https://unix.stackexchange.com/a/495785/264704