Explore Courses Blog Tutorials Interview Questions
0 votes
in DevOps and Agile by (29.3k 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 (50.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 (62.9k 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 user@host: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

Browse Categories