How to tell git which private key to use?

ssh has the -i option to tell which private key file to use when authenticating:

-i identity_file

    Selects a file from which the identity (private key) for RSA or DSA authentication is read.  The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for protocol version 2.  Identity files may also be specified on a per-host basis in the configuration file.  It is possible to have multiple -i options (and multiple identities specified in configuration files).

Is there a similar way to tell git which private key file to use on a system with multiple private keys in the ~/.ssh directory?


In ~/.ssh/config, add:

Host github.com
 HostName github.com
 IdentityFile ~/.ssh/id_rsa_github

If the config file is new, you might need to do chmod 600 ~/.ssh/config

Now you can do git clone [email protected]:{ORG_NAME}/{REPO_NAME}.git

  • Where {ORG_NAME} is your GitHub user account (or organization account)'s GitHub URI name.
    • Note that there is a colon : after github.com instead of the slash / - as this is not a URI.
  • And {REPO_NAME} is your GitHub repo's URI name
  • For example, for the Linux kernel this would be git clone [email protected]:torvalds/linux.git).

NOTE: On Linux and macOS, verify that the permissions on your IdentityFile are 400. SSH will reject, in a not clearly explicit manner, SSH keys that are too readable. It will just look like a credential rejection. The solution, in this case, is:

chmod 400 ~/.ssh/id_rsa_github

Environment variable GIT_SSH_COMMAND

From Git version 2.3.0, you can use the environment variable GIT_SSH_COMMAND like this:

GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example" git clone example

Note that -i can sometimes be overridden by your config file, in which case, you should give SSH an empty config file, like this:

GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example -F /dev/null" git clone example

Configuration core.sshCommand

Since Git version 2.10.0, you can configure this per repo or globally, so you don't have to set the environment variable any more, once you have already cloned the repo:

git config core.sshCommand "ssh -i ~/.ssh/id_rsa_example -F /dev/null"
git pull
git push