How to specify the private SSH-key to use when executing shell command on Git?
None of these solutions worked for me.
Instead, I elaborate on @Martin v. Löwis 's mention of setting a config
file for SSH.
SSH will look for the user's ~/.ssh/config
file. I have mine setup as:
Host gitserv
Hostname remote.server.com
IdentityFile ~/.ssh/id_rsa.github
IdentitiesOnly yes # see NOTES below
And I add a remote git repository:
git remote add origin git@gitserv:myrepo.git
And then git commands work normally for me.
git push -v origin master
NOTES
- The
IdentitiesOnly yes
is required to prevent the SSH default behavior of sending the identity file matching the default filename for each protocol. If you have a file named~/.ssh/id_rsa
that will get tried BEFORE your~/.ssh/id_rsa.github
without this option.
References
- Best way to use multiple SSH private keys on one client
- How could I stop ssh offering a wrong key
Something like this should work (suggested by orip):
ssh-agent bash -c 'ssh-add /somewhere/yourkey; git clone [email protected]:user/project.git'
if you prefer subshells, you could try the following (though it is more fragile):
ssh-agent $(ssh-add /somewhere/yourkey; git clone [email protected]:user/project.git)
Git will invoke SSH which will find its agent by environment variable; this will, in turn, have the key loaded.
Alternatively, setting HOME
may also do the trick, provided you are willing to setup a directory that contains only a .ssh
directory as HOME
; this may either contain an identity.pub, or a config file setting IdentityFile.
Starting from Git 2.3.0 we also have the simple command (no config file needed):
GIT_SSH_COMMAND='ssh -i private_key_file -o IdentitiesOnly=yes' git clone user@host:repo.git
Note the -o IdentitiesOnly=yes
is required to prevent the SSH default behavior of sending the identity file matching the default filename for each protocol as noted in the answer above.
Other people's suggestions about ~/.ssh/config
are extra complicated. It can be as simple as:
Host github.com
IdentityFile ~/.ssh/github_rsa