0 votes
1 view
in Devops and Agile by (29.9k points)
edited by

A rather unusual situation perhaps, but I want to specify a private SSH-key to use when executing a shell (git) command from the local computer.

Basically like this:

git clone [email protected]:TheUser/TheProject.git -key "/home/christoffer/ssh_keys/theuser"

Or even better (in Ruby):

with_key("/home/christoffer/ssh_keys/theuser") do

  sh("git clone [email protected]:TheUser/TheProject.git")


I have seen examples of connecting to a remote server with Net:: SSH that uses a specified private key, but this is a local command. Is it possible?

2 Answers

0 votes
by (51.2k points)

You can use the following syntax

ssh-agent bash -c 'ssh-add /somewhere/yourkey; git clone [email protected]:user/project.git'

If you prefer subshells use

ssh-agent $(ssh-add /somewhere/yourkey; git clone [email protected]:user/project.git)

Git will invoke SSH which will find its agent by the environment variable; this will have the key loaded.

This will help you to specify the private ssh key to use when executing shell command on git.

0 votes
by (63.4k points)

Starting from Git 2.3.0 we also have the simple command (no config file needed):

GIT_SSH_COMMAND='ssh -i private_key_file' git clone [email protected]:repo.git

You may need a restart for the ssh service on your machine.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !