With git 2.10+ (Q3 2016: released Sept. 2d, 2016), you have the possibility to set a config for GIT_SSH_COMMAND
(and not just an environment variable as described in Rober Jack Will's answer)
See commit 3c8ede3 (26 Jun 2016) by Nguyễn Thái Ngọc Duy (pclouds
).
(Merged by Junio C Hamano -- gitster
-- in commit dc21164, 19 Jul 2016)
A new configuration variable core.sshCommand
has been added to
specify what value for GIT_SSH_COMMAND
to use per repository.
core.sshCommand:
If this variable is set, git fetch
and git push
will use the specified command instead of ssh
when they need to connect to a remote system.
The command is in the same form as the GIT_SSH_COMMAND
environment variable and is overridden when the environment variable is set.
It means the git pull
can be:
cd /path/to/my/repo/already/cloned
git config core.sshCommand 'ssh -i private_key_file'
# later on
git pull
When cloning a new repo, where there is not yet any .git/config
to modify, can first set it for just one command like git clone
or git submodule add
:
git -c core.sshCommand="ssh -i private_key_file" clone host:repo.git
Once the repo exists you can set the option permanently in the .git/config
:
cd <repo or submodule you just cloned>
git config core.sshCommand "ssh -i private_key_file"
This is easier than setting a GIT_SSH_COMMAND
environment variable, which, on Windows, as noted by Mátyás Kuti-Kreszács, would be
set "GIT_SSH_COMMAND=ssh -i private_key_file"
For all those commands, you can add a -o IdentitiesOnly=yes
to limit SSH to the the private/public key you are specifying:
git config core.sshCommand 'ssh -i private_key_file -o IdentitiesOnly=yes'
# or
git -c core.sshCommand="ssh -i private_key_file -o IdentitiesOnly=yes" clone host:repo.git
# or
set "GIT_SSH_COMMAND=ssh -i private_key_file -o IdentitiesOnly=yes"
gsullins suggests in the comments to adds to the .zshrc
the following alias:
alias git.key1="git config core.sshCommand 'ssh -i <absolute path to private key>'"
As noted by Jaredo Mills in a comment:
One pitfall: if you mirror your repo to more than one host (Github, Gitlab), with different private keys, this method will send the wrong key.
The key is not associated with the repo, but with a username and hostname. ~/.ssh/config
is the right place to get the association right, and it has the right matching capabilities for the job (see man ssh_config
).
See HeyWatchThis's answer for illustration.
-i
option likessh
does. – Urethragit config core.sshCommand 'ssh -i private_key_file'
. See my answer below – Scaremonger