By Christoffer

2010-12-30 19:42:01 8 Comments

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?


@Peyman Mahdavi 2016-12-25 22:16:09

In Windows with Git Bash you can use the following to add a repository

ssh-agent bash -c 'ssh-add "key-address"; git remote add origin "rep-address"'

for example:

ssh-agent bash -c 'ssh-add /d/test/PrivateKey.ppk; git remote add origin [email protected]:test/test.git'

Which private key is in drive D, folder test of computer. Also if you want to clone a repository, you can change git remote add origin with git clone.

After enter this to Git Bash, it will ask you for passphrase!

Be Aware that openssh private key and putty private key are different!

If you have created your keys with puttygen, you must convert your private key to openssh!

@VonC 2016-07-20 06:47:10

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.


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

You can even set it for just one command like git clone:

git -c core.sshCommand="ssh -i private_key_file" clone host:repo.git

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"

@VonC 2016-08-04 11:03:06

@Flimm release dates:…

@Flimm 2016-11-10 10:13:05

It has been released.

@VonC 2016-11-10 10:16:58

@Flimm yes: that is what my revision ( mentions.

@Flimm 2016-11-10 10:20:12

Yeah, but the comments haven't been deleted. I've deleted my old comment and flagged the other comments as "obsolete".

@WeakPointer 2018-03-08 23:02:43

Works. Folks should consider this the best answer. Once issued, it can be informative to diff the .git/config file with a version copied to /tmp beforehand. A new entry has been created: sshCommand = ... For what it's worth, I used 'git config core.sshCommand "ssh -i $HOME/.ssh/privatekeyfile".

@Spanky 2018-12-06 19:49:46

Only works with an existing git directory. Otherwise you need to set it globally which isn't really what you want.

@dav_i 2020-01-09 16:33:48

@Spanky You can do the inline command git -c core.sshCommand="ssh -i private_key_file" clone host:repo.git followed by the config set git config core.sshCommand 'ssh -i private_key_file'

@Wagner Patriota 2020-03-01 04:38:12

This is definitely the best answer!

@Nickolay 2020-08-17 01:18:43

Spanky's right that the snippet following the "It means the git clone can be:" is incorrect. git config doesn't work outside of a git working directory.

@Robert Jack Will 2015-04-20 17:03:30

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 [email protected]: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.

@ted 2015-11-16 18:28:40

I get cannot run ssh -i /home/vagrant/.ssh/git: No such file or directory though it exists 444 Nov 16 18:12 /home/vagrant/.ssh/git from ls -l /home/vagrant/.ssh/git

@Yash 2016-02-15 12:43:08

@ted: chmod 400 /home/vagrant/.ssh/git

@Lasse Meyer 2016-07-25 10:55:56

Nice and easy solution. I suggest creating an alias if you need to do this a lot.

@Franklin Yu 2016-08-14 16:28:36

@Pierre 2016-08-30 16:46:25

Perfect solution and works without any issues in cygwin

@Optimae 2017-10-08 02:53:31

Great solution for managing multiple repositories, especially if you have them on the same account with different keys.

@eonil 2017-12-10 14:48:45

Don't forget to chmod 400 <path-to-private-key-file>. Otherwise git command may fail with no special error message...

@Nam G VU 2018-07-24 07:33:35

This is my favorite answer ^^

@shijin 2018-11-29 13:49:23

This is the best solution, consider you want to pull the code later, GIT_SSH_COMMAND='ssh -i private_key_file' git pull origin branch_name Its simple and it works.

@hmacias 2018-12-06 17:04:26

This worked for me using Git 2.13.6 on Mac. I was able to clone a remote repo over a SSH forward proxy. Thanks! Note: I only had to export GIT_SSH_COMMAND='ssh -i private_key_file' though.

@Emi-C 2019-11-22 11:56:04

Please note that also .ssh folder has to be granted permissions, besides the subfolder as mentioned above... so be sure to run chmod 400 path/to/.ssh too...

@robinst 2020-01-06 03:23:25

It would be good if this answer also included -o IdentitiesOnly=yes to make sure that the key specified with -i gets used (as opposed to a key from SSH agent).

@rpivovar 2020-03-31 13:30:52

this saved my life.

@Rafael Corrêa Gomes 2020-05-13 01:44:25

I just needed to add the key then run the git clone again.

ssh-add ~/.ssh/id_rsa_mynewkey
git clone [email protected]:mycompany/myrepo.git

@Mike Zygal 2020-04-24 08:30:09

The problem with this method is, at least when running by bash.exe on Windows, that it will create a new process every time which will remain dormant.

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

If you want want to use that for syncig repo on schedule then you need to add "&& ssh-agent -k" at the end.

Something like:

ssh-agent bash -c 'ssh-add C:/Users/user/.ssh/your_key; git -C "C:\Path\to\your\repo" pull && ssh-agent -k' 

ssh-agent -k will kill the process when it's done.

@Anto Khan 2020-03-04 16:22:29

You can try sshmulti npm package for maintaining multiple ssh key.

@RtmY 2020-02-29 21:23:24

A lot of good answers, but some of them assume prior administration knowledge.

I think it is important to explicitly emphasize that if you started your project by cloning the web URL -<user-name>/<project-name>.git
then you need to make sure that the url value under [remote "origin"] in the .git/config was changed to the SSH URL (see code block below).

With addition to that make sure that you add the sshCommmand as mentioned below:

[email protected]:~/workspace/project-name/.git$ cat config
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    sshCommand = ssh -i ~/location-of/.ssh/private_key -F /dev/null <--Check that this command exist
[remote "origin"]
    url = [email protected]:<user-name>/<project-name>.git  <-- Make sure its the SSH URL and not the WEB URL
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master

Read more about it here.

@Chakradar Raju 2020-05-12 05:37:14

Thank you so much, spent so much time trying to figure out why git is not using ssh key. I don't understand why github gives https url as default in clone button.

@Malcolm 2020-07-22 19:00:54

Solid answer, provides info for project level config instead of system wide config. Other answers seem to ignore that you basically only run into this problem if you don't have a system wide configuration!

@carlsborg 2019-01-18 15:45:33

GIT_SSH_COMMAND="ssh -i /path/to/git-private-access-key" git clone $git_repo


export GIT_SSH_COMMAND="ssh -i /path/to/git-private-access-key"
git clone REPO
git push

@rodzmkii 2019-05-09 20:31:39

The problem is when you have different remote repositories on the same host (say, and you want to interact with them using different ssh keys (i.e. different GitHub accounts).

In order to do that:

  1. First you should declare your different keys in ~/.ssh/config file.

    # Key for usual repositories on
    User git
    IdentityFile ~/.ssh/id_rsa
    # Key for a particular repository on
    Host XXX
    User git
    IdentityFile ~/.ssh/id_other_rsa

    By doing this you associate the second key with a new friendly name "XXX" for

  2. Then you must change the remote origin of your particular repository, so that it uses the friendly name you've just defined.

    Go to your local repository folder within a command prompt, and display the current remote origin:

    >git remote -v
    origin  [email protected]:myuser/myrepo.git (fetch)
    origin  [email protected]:myuser/myrepo.git (push)

    Then change origin with:

    >git remote set-url origin [email protected]:myuser/myrepo.git
    >git remote -v
    origin  [email protected]:myuser/myrepo.git (fetch)
    origin  [email protected]:myuser/myrepo.git (push)

    Now you can push, fetch... with the right key automatically.

@jamescampbell 2019-06-18 13:13:23

This is the most "right" answer in my mind, where you organize connections and keys in your ssh config file that is best practice and supportable long term.

@Craig.C 2019-11-20 11:05:30

Other solutions seem like workarounds, this is using great feature the tool supports.

@Mátyás Kuti-Kreszács 2020-01-07 09:31:52

To have GIT_SSH_COMMAND environment variable work under Windows instead of:

set GIT_SSH_COMMAND="ssh -i private_key_file"


set "GIT_SSH_COMMAND=ssh -i private_key_file"

The quote has to be like

set "variable=value" 

Some backgorund:

@cgnorthcutt 2018-11-21 16:51:44

If none of the other solutions here work for you, and you have created multiple ssh-keys, but still cannot do simple things like

git pull

then assuming you have two ssh key files like


then inside of the git repo, try:

# Run these commands INSIDE your git directory
eval `ssh-agent -s`
ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_rsa_other_key

and also make sure your github default username and userid are correct by:

# Run these commands INSIDE your git directory
git config "Mona Lisa"
git config "[email protected]"

See for more more information.

@cgnorthcutt 2019-02-14 23:09:13

Note if you get Could not open a connection to your authentication agent., try $ eval `ssh-agent -s`, and try again.

@Ben Cartwright 2019-02-26 01:34:59

For those who are lost, the ssh-add command trick worked for me. Add's the identity key to the list of those which are tried when ssh authenticates. This worked for me well!

@tripleee 2020-03-04 19:59:50

Why do you think it matters in which directory you run ssh-add?

@cgnorthcutt 2020-03-05 20:52:13

@BenCartwright Because you are modifying local settings, not global settings. This approach modifies .git inside the repo not the git program globally. You can use --global to set global username and email.

@cristobal 2019-03-14 12:41:10

if you have directory on your path where you want to sign with a given identifyfile you can specify to use a specific identify file via the .ssh/config file by setting the ControlPath e.g.:

  ControlPath ~/Projects/work/**
  IdentityFile ~/.ssh/id_work
  User git

Then ssh will use the specified identity file when doing git commands under the given work path.

@cristobal 2019-05-03 06:41:13

Found out later that you can also set the properties ControlMaster auto and ControlPersist yes, so that you do not need to retype the password every time. Found the info in this article

@penduDev 2019-02-14 07:53:24

Here's the ssh key hack i found while finding solution to this problem:

For example you have 2 different set of keys:

key1,, key2,

Keep these keys in your .ssh directory

Now in your .bashrc or .bash_profile alias file, add these commands

alias key1='cp ~/.ssh/key1 id_rsa && cp ~/.ssh/'

alias key2='cp ~/.ssh/key2 id_rsa && cp ~/.ssh/'

Voila! You have a shortcut to switch keys whenever you want!

Hope this works for you.

@Sergey Nemchinov 2020-08-10 08:54:12

Please add information about how to use these keys using git

@penduDev 2020-08-20 05:50:32

@SergeyNemchinov you just have to run key1 or key2 on the terminal and respective key pairs become the default keys for your system.. then you don't need to explicitly specify which key you want to use with git. It use the default key.

@l3x 2018-12-31 05:40:32

If you're like me, you can:

  • Keep your ssh keys organized

  • Keep your git clone commands simple

  • Handle any number of keys for any number of repositories.

  • Reduce your ssh key maintenance.

I keep my keys in my ~/.ssh/keys directory.

I prefer convention over configuration.

I think code is law; the simpler it is, the better.

STEP 1 - Create Alias

Add this alias to your shell: alias git-clone='GIT_SSH=ssh_wrapper git clone'

STEP 2 - Create Script

Add this ssh_wrapper script to your PATH:

# Filename: ssh_wrapper

if [ -z ${SSH_KEY} ]; then
    SSH_KEY=''  # <= Default key
ssh -i "${SSH_KEY}" "[email protected]"


Use key: git-clone

The following example also uses the key (by default):


Use key: git-clone [email protected]:dave_andersen/exchange.git


Change the default SSH_KEY in the ssh_wrapper script to what you use most of the time. That way, you don't need to use the KEY variable most of the time.

You may think, "Hey! That's a lot going on with an alias, a script and some directory of keys," but for me it's convention. Nearly all my workstations (and servers for that matter) are configured similarly.

My goal here is to simplify the commands that I execute regularly.

My conventions, e.g., Bash scripts, aliases, etc., create a consistent environment and helps me keep things simple.

KISS and names matter.

For more design tips check out Chapter 4 SOLID Design in Go from my book:

Hope that helps. - Lex

@gajanan malvade 2018-12-07 06:46:06

You need to create a ~/.ssh/config as below

Host <Your bitbucket server>
User <userid>
Hostname <Your bitbucket server as above>
IdentitiesOnly yes
IdentityFile ~/.ssh/id_rsa<file> This is your private key file

permission as below

-rw------- $HOME/.ssh/config

Add your public key into your git (cat ~/.ssh/id_rsa_pub [or simillar name])

and then git clone as below

git clone ssh://[email protected]/userid/test.git

@HeyWatchThis 2012-06-28 19:44:51

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
    IdentityFile ~/.ssh/id_rsa.github
    IdentitiesOnly yes # see NOTES below

And I add a remote git repository:

git remote add origin [email protected]:myrepo.git

And then git commands work normally for me.

git push -v origin master


  • 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.


@Gopinath M.R 2013-07-15 23:46:55

I found that when you specify multiple keys using .ssh/config, you need to use host friend name in line "Host" as part of "git remote add" command. If line is "Host stg", then you need to use git remote add <someName> [email protected]:/path_to_git_repo.git ". If you use exact server name like [email protected]:/path_to_git_repo.git, the config file is not picked by git. Hence, it is not picking private key file correctly. I tried this by pushing same content to github and heroku and works only when you give friendly name in "git remote add"

@Karsten 2014-07-15 09:40:57

I wasn't sure about the Host for github. I found this link:

@Bruno Bronosky 2014-07-29 16:29:52

@JonnyReeves edits introduced mismatched hostnames. Pushing to gitserv will not match the ssh config Host entry for remote or Therefore the intended IdentityFile will not be used. I'm going to edit this answer.

@e271p314 2014-09-09 14:37:46

Take a look here if you want to have few key files for few git repositories

@Enze Chi 2015-03-30 23:08:14

Hope the SSH config solution could support get account name from this format `[email protected]:<account_name>/some_repo.git that you don't have to modify the host for different account names when do the clone.

@sid-kap 2015-08-31 14:40:28

I don't understand why IdentitiesOnly is necessary. As I understand it, by adding this host to the config file, it will add this ssh key to a list of keys that it will try, i.e. it will first try ~/.ssh/identity, ~/.ssh/id_dsa, ~/.ssh/id_ecdsa and ~/.ssh/id_rsa and then it will try ~/.ssh/id_rsa.github. Is there anything wrong with it trying id_rsa before id_rsa.github, as long as it eventually tries id_rsa.github?

@starbeamrainbowlabs 2016-04-25 09:55:02

Umm this doesn't work for me. When I do a git pull from my private repo, git ignores my .ssh/config file completely and tries id_rsa instead, which is the wrong key.

@Stefan Avey 2016-05-22 19:51:01

I had all of this except for IdentitiesOnly and it worked for a while but then one day stopped working and was trying to use my default key in id_rsa. IdentifiesOnly does seem to be important.

@MauganRa 2016-08-09 13:03:44

You could use Host and keep using the original URL

@Guillaume S. 2016-12-27 10:19:13

For some reason, this worked for me, but I add to SSH-login to the Git server first for the identifyFile to be used (Probably has to do with the known_hosts not being populated). So, after doing that, and before running your git clone ... command, run: ssh {hostname}

@Roman Susi 2018-05-21 05:24:23

Also User may be required in the config entry

@miguelmorin 2018-06-21 11:30:50

This worked for me after two changes. If the config file is new, don't forget to do chmod 600 ~/.ssh/config (see here). And if you are using GitHub, replace Host gitserv with Host, omit Hostname, and add remote with git remote add origin [email protected]:user_name/repo_name.git.

@Kevin G. 2018-10-13 16:57:37

IdentitiesOnly yes did it! I was going mad. I tried to setup GitLab with a custom SSH key - this should be part of the official documentation.

@Ed Neville 2018-11-09 21:25:21

This is exactly what I was after. Completely forgot about ~/.ssh/config. Thank you kind stranger.

@Ignacio Vazquez 2018-11-26 14:30:05

Is it possible same host but different subfolders ? ie "Host" but different keys for different projects

@Paul Leclerc 2018-12-18 10:24:11

The fact to add a new remote did the trick for me. For the context : I add a new key during a project and wanting to push with it.

@iBug 2019-03-28 16:10:13

To save some more characters, add User git into that configuration item and just use gitserv:myrepo.git as remote URL.

@cowlinator 2020-04-09 19:37:32

This is the only answer that also works with Windows if you are using the ssh client that comes with Git (located at %ProgramFiles%\Git\usr\bin\ssh.exe by default). Modify or create the config file located at %USERPROFILE%\.ssh\config.

@DarkTrick 2020-07-07 13:28:35

I needed to use Host instead of Hostname. I.e. Host\nHost

@Dan Dascalescu 2014-09-19 00:19:06

To sum up answers and comments, the best way to set up git to use different key files and then forget about it, which also supports different users for the same host (e.g. a personal GitHub account and a work one), which works on Windows as well, is to edit ~/.ssh/config (or c:\Users\<your user>\.ssh\config) and specify multiple identities:

IdentityFile /path/to/your/personal/github/private/key
User dandv

Host github-work
IdentityFile /path/to/your/work/github/private/key
User workuser

Then, to clone a project as your personal user, just run the regular git clone command.

To clone the repo as the workuser, run git clone [email protected]:company/project.git.

@hroptatyr 2015-03-27 12:34:19

I downvoted you because everything you say is already covered in the answers above, and in my eyes, even more clearly. For instance, why exactly do you define the User to e dandv and workuser, respectively?

@rudimeier 2015-03-27 13:03:51

You answered a 4 year old question with no new informations and you are claiming that your answer is "the best way". Moreover you downvoted and hassled other users to remove their answer ... just to get your one pushed up.

@Dan Dascalescu 2015-03-28 07:50:02

@hroptatyr: I've used dandv and workuser to support my example, "e.g. a personal GitHub account and a work one". dandv is my GitHub username.

@jthill 2015-05-08 15:39:41

You've actually got the right idea here, but this won't work. You have to use user 'git'. The problem is, you're duplicating thamster's reply from 2012.

@David Moles 2016-04-18 17:12:53

I think it's a better answer than @thamster's, if only because it explains host aliases.

@winni2k 2017-02-17 11:14:01

I like this answer. However, for me this only works if I add IdentitiesOnly yes to my ssh config file.

@w..k 2017-10-31 15:15:48

If SSH port number is not 22(default), add Port xx in ~/.ssh/config

In my case (synology),

Host my_synology
    IdentityFile ~/.ssh/id_rsa_xxxx
    User myname
    Port xx

Then clone using Host title in config. ("my_synology". to avoid @chopstik 's "*")

git clone my_synology:path/to/repo.git

@Alupotha 2017-09-02 00:07:35

for the gitlab RSAAuthentication yes

  RSAAuthentication yes
  IdentityFile ~/.ssh/your_private_key_name
  IdentitiesOnly yes

doc is here

@rbennell 2019-04-25 05:57:20

doesn't appear to be mentioned on the link you provided any more

@sdkks 2017-08-21 03:15:40

I use zsh and different keys are loaded to my zsh shell's ssh-agent automatically for other purposes (i.e. access to remote servers) on my laptop. I modified @Nick's answer and I'm using it for one of my repos that needs to be refreshed often. (In this case it's my dotfiles which I want same and latest version across my all machines, wherever I'm working.)

bash -c 'eval `ssh-agent`; ssh-add /home/myname/.dotfiles/gitread; ssh-add -L; cd /home/myname/.dotfiles && git pull; kill $SSH_AGENT_PID'
  • Spawn an ssh-agent
  • Add read-only key to agent
  • Change directory to my git repo
  • If cd to repo dir is successful, pull from remote repo
  • Kill spawned ssh-agent. (I wouldn't want many of agents lingering around.)

@David 2017-01-12 12:14:40

As stated here:

You can configure it per-repo:

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

@Dominic 2017-03-23 12:26:07

What does -F /dev/null do? As far as I can see this will change configFile from the ~/.ssh/config default but why is that desired? To ensure a sandboxed command?

@David 2017-03-23 16:04:24, specifies no config file, so when git will run ssh, no config file will be passed (in fact it's a kind of sandbox mode, just ignore user config default options) Original thread in superuser has more info about -F

@lostcitizen 2019-03-04 18:35:44

The one I was looking for. Thanks!

@Cobra vs Ninja 2019-04-10 08:49:29

AAAAA+ solution for working in kuber environment. Thanks!

@Arka Prava Basu 2019-12-27 13:34:18

Hi Do you know how to propagate this to a submodule?

@z.a. 2020-01-27 04:58:44

How can I put this is bash_profile as alias? Always getting errors.

@tripleee 2020-03-04 19:57:44

Why would you put this in your .bash_profile as an alias? You just run it once (for each repo). In general, use functions instead of aliases and your life will be easier; but both are slightly hard if you are confused about quoting.

@Martin v. Löwis 2010-12-30 19:48:28

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, or a config file setting IdentityFile.

@Christoffer 2010-12-30 19:55:10

But this will add the key permanently as an accepted SSH-key, right? I want to avoid that so that theuser2 can't mess with theuser's projects. It's for a web application so it's not practical to use different OS-users, which would have been the best option.

@Martin v. Löwis 2010-12-30 19:56:00

No, when git completes, ssh-agent terminates, and the key is forgotten.

@Christoffer 2010-12-30 19:58:42

Wonderful! :) Thank you very much.

@Mohit 2011-09-19 19:02:24

this command does'not work on windows git bash. It says syntax error near unexpected token 'ssh-add'

@orip 2011-11-10 00:00:44

Fixed command line (for windows or linux) would be something like: ssh-agent bash -c 'ssh-add sshkey; git clone url'

@Adam 2013-05-05 20:18:36

This works fine on my desktop *nix machines, but fails on several servers that are virgin installs of current Debian. @HeyWatchThis's answer seems to work everywhere (although it's permanent where this one is temporary)

@Sohaib 2014-12-11 13:47:35

bash crashes on windows for me (using git bash environment variables). Is there a workaround for windows.

@kynan 2015-10-28 16:48:29

I've fixed the syntax of the first command line: it should be $( ... ) to launch a subshell.

@Johannes 'fish' Ziemke 2015-12-28 11:55:29

The ssh-agent $(..) syntax isn't working for me and I'm not sure how this is suppose to work: (ba)sh should execute the commands inside $(..) first, then run ssh-agent with the output as parameter.

@Starx 2016-08-31 04:48:46

How will this solution work if the key has a passphrase?

@cyl19910101 2016-10-05 11:15:50

Thanks a lot, this works for me. My OS X is pretty wired that I can only use the ssh-agent way you mentioned to access the git server, directly using git clone will get Permission denied (publickey,gssapi-keyex,gssapi-with-mic). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. even the private key is just in ~/.ssh/id_rsa and ssh-add -l has showed it correctly. Do you have any idea about this?

@Jistanidiot 2017-09-21 18:54:55

Unfortunately instead of removing the key, it left it there. You should add a ssh-add -d /path/to/key at the end.

@Silas S. Brown 2018-03-07 11:20:10

The $(..) syntax probably doesn't do what you expect: it runs the commands inside first and sends their output to ssh-agent. This might happen to work anyway if another ssh-agent happens to be already running, but then the new key will be left in the agent (unless you add ssh-add -d to take it out) and the answer becomes ssh-add /somewhere/yourkey && git clone [email protected]:user/project.git ; ssh-add -d /somewhere/yourkey (and we assume ssh-agent is already running, and note the use of && rather than ;). But that's moot because the bash -c version is correct.

@Artem Russakovskii 2018-12-28 18:16:51

This solution stopped working for me for some reason after I upgraded from OpenSUSE 42.3 to 15.0. I switched to, which is working well.

@Jacktose 2019-01-08 19:45:57

You also accomplish this with ssh-add -t 60; git clone [email protected]:user/project.git. That will just expire the key after 60 seconds.

@philfreo 2013-09-17 00:39:03

Other people's suggestions about ~/.ssh/config are extra complicated. It can be as simple as:

  IdentityFile ~/.ssh/github_rsa

@Flimm 2015-07-03 14:56:52

You need the IdentitiesOnly option, too.

@emory 2017-05-04 11:52:04

@EnzeChi you can have multiple github accounts by manipulating the remotes: git remote add ssh://personal/org/proj.git && git remote add ssh://corporate/org/proj.git. Then you config looks like Host personal HostName ... Host corporate HostName

@emory 2017-05-04 11:53:45

@EnzeChi I do something similar so that I use 2 different ssh keys - one for fetching and the other for pushing. The fetch does not have a passphrase. The push does.

@AlbinoDrought 2020-08-18 04:16:21

Mine works without the IdentitiesOnly option. Can someone explain why this should be required?

@Jamie 2013-01-15 16:58:50

I went with the GIT_SSH environment variable. Here's my wrapper, similar to that from Joe Block from above, but handles any amount of arguments.

File ~/

ssh -i ~/.ssh/gitkey_rsa "[email protected]"

Then, in my .bashrc, add the following:

export GIT_SSH=~/

@Jigar Shah 2013-02-11 06:48:17

I did set this on .bashrc. But when I login to openshift instance, it does not seems to be calling it. Am I missing something ?

@ap1234 2016-07-26 00:24:46

It fails with an error for me.. its not able to find the script event though its there.. not sure whats going on...error: cannot run /tmp/ No such file or directory

@Tahir Akhtar 2017-10-27 13:15:14

If you face "No such file or directory" error, put full path of, for example /home/ubuntu/

@dan-man 2019-02-21 12:53:01

you might want to add -o StrictHostKeyChecking=no to the ssh command

@Paul McMurdie 2015-02-21 00:05:24

Many of these solutions looked enticing. However, I found the generic git-wrapping-script approach at the following link to be the most useful:

How to Specify an ssh Key File with the git command

The point being that there is no git command such as the following:

git -i ~/.ssh/thatuserkey.pem clone [email protected]:/git/repo.git

Alvin's solution is to use a well-defined bash-wrapper script that fills this gap: -i ~/.ssh/thatuserkey.pem clone [email protected]:/git/repo.git

Where is:


# The MIT License (MIT)
# Copyright (c) 2013 Alvin Abad

if [ $# -eq 0 ]; then
    echo "Git wrapper script that can specify an ssh-key file
Usage: -i ssh-key-file git-command
    exit 1

# remove temporary file on exit
trap 'rm -f /tmp/.git_ssh.$$' 0

if [ "$1" = "-i" ]; then
    SSH_KEY=$2; shift; shift
    echo "ssh -i $SSH_KEY \[email protected]" > /tmp/.git_ssh.$$
    chmod +x /tmp/.git_ssh.$$
    export GIT_SSH=/tmp/.git_ssh.$$

# in case the git command is repeated
[ "$1" = "git" ] && shift

# Run the git command
git "[email protected]"

I can verify that this solved a problem I was having with user/key recognition for a remote bitbucket repo with git remote update, git pull, and git clone; all of which now work fine in a cron job script that was otherwise having trouble navigating the limited-shell. I was also able to call this script from within R and still solve the exact same cron execute problem (e.g. system("bash -i ~/.ssh/thatuserkey.pem pull")).

Not that R is the same as Ruby, but if R can do it... O:-)

@BlueBird 2015-05-27 05:31:28

Looks like great! I will test this and reply back.

@David Moles 2016-04-18 17:18:12

Apart from the syntax, how is this better than GIT_SSH_COMMAND="ssh -i ~/.ssh/thatuserkey.pem" git clone clone [email protected]:/git/repo.git as per Robert Jack Will's answer?

@rudimeier 2011-10-28 12:09:46

You could use GIT_SSH environment variable. But you will need to wrap ssh and options into a shell script.

See git manual: man git in your command shell.

@chopstik 2013-05-06 04:34:54

When you need to connect to github with a normal request (git pull origin master), setting the Host as * in ~/.ssh/config worked for me, any other Host (say, "github" or "gb") wasn't working.

Host *
    User git
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_xxx

@lionello 2014-06-26 04:22:53

Might as well leave the entire "Host *" line out then.

@David Moles 2016-04-18 17:15:03

It probably wasn't working because it didn't match your remote URL. If you want to use Host my-host-alias, you have to set [email protected]:[username]/[repo].git.

@thamster 2012-10-01 21:55:40

Way better idea to add that host or ip to the .ssh/config file like so:

Host (a space separated list of made up aliases you want to use for the host)
    User git
    Hostname (ip or hostname of git server)
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_(the key you want for this repo)

@Joe Block 2013-01-03 22:27:58

That's useful, but makes you use the repo key for all interaction with that hostname. If there are other repos on the same server that require different keys, using a wrapper and telling git to use it with GIT_SSH is better.

@blockloop 2013-12-18 17:35:11

That's not necessarily true. I use multiple keys for Github - one for work and one for my personal account. You don't have to put a domain name for "Host". You can put any kind of alias you want. For example, I use gh-home and gh-work as my hostnames and when I clone I use, for example, git clone [email protected]:repo/project.git In my ~/.ssh/config I have two sections that both use for HostName. They just have different IdentityFile and Host

@ktec 2015-03-28 16:58:06

@brettof86 this strategy works for the most part, but what do you do when a repository you are checking out depends on a gem which is also hosted on github? The the reference to the github repo in the Gemfile wont contain your "alias", well not unless you want to break things for other developers on the project...

@Climbs_lika_Spyder 2015-06-04 18:43:54

@brettof86 I also have two different github accounts (work, home), but I cannot get the example to work for me. Can you post a sample of having two?

@blockloop 2015-06-05 19:50:23

@Climbs_lika_Spyder here's what's in my ~/.ssh/config

@Climbs_lika_Spyder 2015-06-08 15:20:55

@brettof86 it says this paste has been removed :(

@qodeninja 2015-07-29 23:38:21

@Climbs_lika_Spyder the gist is missing now too -___-

@blockloop 2015-08-06 22:40:16

I can paste it here, but it's going to be ugly... Host work-gh HostName PreferredAuthentications publickey IdentityFile ~/.ssh/work_id_rsa Host HostName PreferredAuthentications publickey IdentityFile ~/.ssh/id_rsa

@blockloop 2015-08-06 22:41:17

@Student of Science 2020-06-12 20:53:14

Your answer so helpeful that I signed in just to give thumps up!! This was really useful

@Joe Block 2012-02-17 01:32:57

Contents of my_git_ssh_wrapper:


ssh -i /path/to/ssh/secret/key $1 $2

Then you can use the key by doing:

GIT_SSH=my_git_ssh_wrapper git clone [email protected]:TheUser/TheProject.git

@Beka 2014-04-26 08:54:56

Very good solution if you have more than one account at the same domain, which other solutions don't handle well

@Shiva 2014-05-06 23:40:11

Nice solution. You can also simplify this with > GIT_SSH=my_git_ssh_wrapper; git clone [email protected]:TheUser/TheProject.git

@piotrekkr 2014-05-19 08:14:09

This solution also covers situations when you want to use git from account without home directory.

@ton 2015-04-10 22:41:35

Fantastic. You can use this way to private servers too: GIT_SSH="git_wrapper" git clone ssh://[email protected]/path/to/project"

@ChatterOne 2016-06-22 12:37:24

This is the only way that worked for me in a cygwin environment

Related Questions

Sponsored Content

18 Answered Questions

[SOLVED] How do I access my SSH public key?

  • 2010-09-30 06:03:56
  • sscirrus
  • 974863 View
  • 644 Score
  • 18 Answer
  • Tags:   git ssh rsa

17 Answered Questions

[SOLVED] How to use SSH to run a local shell script on a remote machine?

18 Answered Questions

[SOLVED] Git error: "Host Key Verification Failed" when connecting to remote repository

  • 2012-11-13 15:26:36
  • bootsz
  • 392213 View
  • 236 Score
  • 18 Answer
  • Tags:   git ssh ssh-keys

12 Answered Questions

[SOLVED] How can I specify a branch/tag when adding a Git submodule?

  • 2009-11-22 04:55:48
  • Ivan
  • 553386 View
  • 789 Score
  • 12 Answer
  • Tags:   git git-submodules

13 Answered Questions

[SOLVED] How to echo shell commands as they are executed

14 Answered Questions

[SOLVED] Specify an SSH key for git push for a given domain

  • 2011-10-28 09:57:04
  • Confusion
  • 244942 View
  • 354 Score
  • 14 Answer
  • Tags:   git ssh gitolite

20 Answered Questions

[SOLVED] Best way to use multiple SSH private keys on one client

  • 2010-03-10 18:40:58
  • Justin
  • 462544 View
  • 894 Score
  • 20 Answer
  • Tags:   ssh ssh-keys openssh

20 Answered Questions

[SOLVED] How to call shell commands from Ruby

  • 2008-08-05 12:56:52
  • CodingWithoutComments
  • 539055 View
  • 1105 Score
  • 20 Answer
  • Tags:   ruby shell interop

6 Answered Questions

1 Answered Questions

[SOLVED] Using git over ssh won't pick up private key

  • 2014-10-30 17:35:07
  • Jonathan.Brink
  • 1411 View
  • 2 Score
  • 1 Answer
  • Tags:   linux git shell ssh

Sponsored Content