How to tell git which private key to use?











up vote
510
down vote

favorite
212












ssh has the -i option to tell which private key file to use when authenticating:




-i identity_file


    Selects a file from which
    the identity (private key) for RSA or DSA authentication is read. 
    The default is ~/.ssh/identity for protocol version 1,
    and ~/.ssh/id_rsa and ~/.ssh/id_dsa for protocol version 2. 
    Identity files may also be specified on a per-host basis
    in the configuration file.  It is possible to have multiple -i options
    (and multiple identities specified in configuration files).



Is there a similar way to tell git which private key file to use on a system with multiple private keys in the ~/.ssh directory?










share|improve this question




















  • 3




    See this question in StackOverflow as well.
    – Flimm
    May 8 '15 at 9:46






  • 2




    Also related serverfault.com/questions/194567/…
    – Machavity
    Jun 28 '16 at 14:51















up vote
510
down vote

favorite
212












ssh has the -i option to tell which private key file to use when authenticating:




-i identity_file


    Selects a file from which
    the identity (private key) for RSA or DSA authentication is read. 
    The default is ~/.ssh/identity for protocol version 1,
    and ~/.ssh/id_rsa and ~/.ssh/id_dsa for protocol version 2. 
    Identity files may also be specified on a per-host basis
    in the configuration file.  It is possible to have multiple -i options
    (and multiple identities specified in configuration files).



Is there a similar way to tell git which private key file to use on a system with multiple private keys in the ~/.ssh directory?










share|improve this question




















  • 3




    See this question in StackOverflow as well.
    – Flimm
    May 8 '15 at 9:46






  • 2




    Also related serverfault.com/questions/194567/…
    – Machavity
    Jun 28 '16 at 14:51













up vote
510
down vote

favorite
212









up vote
510
down vote

favorite
212






212





ssh has the -i option to tell which private key file to use when authenticating:




-i identity_file


    Selects a file from which
    the identity (private key) for RSA or DSA authentication is read. 
    The default is ~/.ssh/identity for protocol version 1,
    and ~/.ssh/id_rsa and ~/.ssh/id_dsa for protocol version 2. 
    Identity files may also be specified on a per-host basis
    in the configuration file.  It is possible to have multiple -i options
    (and multiple identities specified in configuration files).



Is there a similar way to tell git which private key file to use on a system with multiple private keys in the ~/.ssh directory?










share|improve this question















ssh has the -i option to tell which private key file to use when authenticating:




-i identity_file


    Selects a file from which
    the identity (private key) for RSA or DSA authentication is read. 
    The default is ~/.ssh/identity for protocol version 1,
    and ~/.ssh/id_rsa and ~/.ssh/id_dsa for protocol version 2. 
    Identity files may also be specified on a per-host basis
    in the configuration file.  It is possible to have multiple -i options
    (and multiple identities specified in configuration files).



Is there a similar way to tell git which private key file to use on a system with multiple private keys in the ~/.ssh directory?







ssh git authentication private-key






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 16 '15 at 5:31









G-Man

5,558102257




5,558102257










asked Jan 12 '11 at 18:20









jrdioko

3,19052126




3,19052126








  • 3




    See this question in StackOverflow as well.
    – Flimm
    May 8 '15 at 9:46






  • 2




    Also related serverfault.com/questions/194567/…
    – Machavity
    Jun 28 '16 at 14:51














  • 3




    See this question in StackOverflow as well.
    – Flimm
    May 8 '15 at 9:46






  • 2




    Also related serverfault.com/questions/194567/…
    – Machavity
    Jun 28 '16 at 14:51








3




3




See this question in StackOverflow as well.
– Flimm
May 8 '15 at 9:46




See this question in StackOverflow as well.
– Flimm
May 8 '15 at 9:46




2




2




Also related serverfault.com/questions/194567/…
– Machavity
Jun 28 '16 at 14:51




Also related serverfault.com/questions/194567/…
– Machavity
Jun 28 '16 at 14:51










15 Answers
15






active

oldest

votes

















up vote
558
down vote



accepted










In ~/.ssh/config, add:



host github.com
HostName github.com
IdentityFile ~/.ssh/id_rsa_github
User git


Now you can do git clone git@github.com:username/repo.git.



NOTE: Verify that the permissions on IdentityFile are 400.SSH will reject, in a not clearly explicit manner, SSH keys that are too readable. It will just look like a credential rejection. The solution, in this case, is:



chmod 400 ~/.ssh/id_rsa_github





share|improve this answer



















  • 76




    What if you need to connect to the same host with different keys?
    – Valentin Klinghammer
    Nov 30 '12 at 11:24






  • 6




    @Quelltextfabrik - you can add another section with a different Host: nerderati.com/2011/03/…
    – Ben Challenor
    Dec 4 '12 at 14:17






  • 1




    @Cliff Nop, in my manpage: "HostName: Specifies the real host name to log into. This can be used to specify nicknames or abbreviations for hosts." My ssh version is openssh-6.7p1.
    – Grissiom
    Jan 7 '15 at 2:17






  • 1




    @Grissiom That's exactly what it says. But you seem to understand the meaning backwards. Host (or Match) is required. To create a host nickname you place the nickname in the Host line and the real hostname in the HostName line. Examples: saltycrane.com/blog/2008/11/…
    – Cliff
    Jan 8 '15 at 3:55






  • 7




    If the config file is new, don't forget to do chmod 600 ~/.ssh/config
    – elysch
    Mar 15 '16 at 23:02


















up vote
244
down vote













Environment variable GIT_SSH_COMMAND:



From Git version 2.3.0, you can use the environment variable GIT_SSH_COMMAND like this:



GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example" git clone example


Note that -i can sometimes be overridden by your config file, in which case, you should give SSH an empty config file, like this:



GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example -F /dev/null" git clone example


Configuration core.sshCommand:



From Git version 2.10.0, you can configure this per repo or globally, so you don't have to set the environment variable any more!



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





share|improve this answer



















  • 1




    I had to export the shell variable to an environment variable to make this work, i.e. export GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example", then git clone example
    – Abdull
    Dec 1 '15 at 13:46








  • 6




    @Abdull In Bash, doing the assignment on the same line as the command exports the environment variable for just that command. Try it: example=hello /usr/bin/env | grep example.
    – Flimm
    Jan 8 '16 at 9:50






  • 3




    things have become even better: as of Git 2.10, you can store the command in your Git configuration: stackoverflow.com/a/38474220/520162
    – eckes
    Oct 21 '16 at 7:57






  • 1




    @Noitidart /dev/null is only a valid filename in UNIX-like operating systems, it doesn't work on Windows.
    – Flimm
    Mar 7 '17 at 8:19






  • 1




    If you need multiple keys, the -i parameter can be repeated, and ssh will try each key in turn. git config core.sshcommand "ssh -i /path/to/keyA -i /path/to/keyB". This lets git use different keys with different remote hosts.
    – Mark
    Jun 23 '17 at 3:44


















up vote
73
down vote













There is no direct way to tell git which private key to use, because it relies on ssh for repository authentication. However, there are still a few ways to achieve your goal:



Option 1: ssh-agent



You can use ssh-agent to temporarily authorize your private key.



For example:



$ ssh-agent sh -c 'ssh-add ~/.ssh/id_rsa; git fetch user@host'


Option 2: GIT_SSH_COMMAND



Pass the ssh arguments by using the GIT_SSH_COMMAND environment variable
(Git 2.3.0+).



For example:



$ GIT_SSH_COMMAND='ssh -i ~/.ssh/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no' 
git clone user@host


You can type this all on one line — ignore $ and leave out the .



Option 3: GIT_SSH



Pass the ssh arguments by using the GIT_SSH environment variable to specify alternate ssh binary.



For example:



$ echo 'ssh -i ~/.ssh/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no $*' > ssh
$ chmod +x ssh
$ GIT_TRACE=1 GIT_SSH='./ssh' git clone user@host


Note: The above lines are shell (terminal) command lines which you should paste into your terminal. They will create a file named ssh, make it executable, and (indirectly) execute it.



Note: GIT_SSH is available since v0.99.4 (2005).



Option 4: ~/.ssh/config



Use the ~/.ssh/config file as suggested in other answers in order to specify the location of your private key, e.g.



Host github.com
User git
Hostname github.com
IdentityFile ~/.ssh/id_rsa





share|improve this answer



















  • 1




    // , What if your identity in ssh-agent is forwarded, though, as in this question? superuser.com/questions/971732/…
    – Nathan Basanese
    Sep 11 '15 at 18:06






  • 1




    I've allowed me to reformat this post: IMO this is by far the most comprehensive answer. In its original design, a quick scan suggested the post where describing a single complicated solution to the problem, so I missed it.
    – Alberto
    Jan 21 '16 at 10:01






  • 2




    $ ssh-agent sh -c 'ssh-add ~/.ssh/id_rsa; git fetch user@host' worked for me when nothing else would. Kudos.
    – Daniel Dewhurst
    Sep 11 '17 at 15:24










  • I had to use ~/.ssh/config method, env vars didn't work for me...
    – Greg Dubicki
    Sep 22 '17 at 7:53






  • 1




    GIT_SSH is available since v0.99.4 (August 2005), so basically since Git exists (April 2005).
    – Dominik
    Nov 17 '17 at 8:10


















up vote
32
down vote













Write a script that calls ssh with the arguments you want, and put the filename of the script in $GIT_SSH. Or just put your configuration in ~/.ssh/config.






share|improve this answer

















  • 1




    Another explanation of how to do this.
    – Sithsu
    May 12 '14 at 19:44








  • 1




    ~/.ssh/config Is the way to go.
    – hek2mgl
    May 8 '15 at 13:56










  • I work on a machine (A) from which I git push to a server (B) that only accepts ssh key authentication. While my ~/.ssh/config setup on (A) works perfectly fine when I work directly on that machine, it does not when I login from some other location (C). Using $GIT_SSH and a script solved this problem. Thanks!
    – bsumirak
    Dec 3 '15 at 17:28


















up vote
15
down vote













If you do not want to have to specify environment variables every time you run git, do not want another wrapper script, do not/can not run ssh-agent(1), nor want to download another package just for this, use the git-remote-ext(1) external transport:



$ git clone 'ext::ssh -i $HOME/.ssh/alternate_id git.example.com %S /path/to/repository.git'
Cloning into 'repository'
(...)
$ cd repository
$ git remote -v
origin ext::ssh -i $HOME/.ssh/alternate_id git.example.com %S /path/to/repository.git (fetch)
origin ext::ssh -i $HOME/.ssh/alternate_id git.example.com %S /path/to/repository.git (push)


I consider this solution superior because:




  • It is repository/remote specific

  • Avoid wrapper script bloat

  • Do not need the SSH agent -- useful if you want unattended clones/push/pulls (e.g. in cron)

  • Definitely, no external tool needed






share|improve this answer





















  • // , Excellent solution. I wonder, though, if this would allow one to specify an identity passed through using agent forwarding. Most of my keys are not local to the servers I am using them on. I asked about this here: superuser.com/questions/971732/…
    – Nathan Basanese
    Sep 11 '15 at 18:09










  • The answer deals only with a way of specifying arbitrary command lines to be used as git repositories. IMHO, you should try to sort out your issue using ssh alone first (e.g. "ssh host" should connect using the right key). I will try to provide more info on your other question, though.
    – flaviovs
    Sep 14 '15 at 16:34






  • 1




    This answer was exactly what I needed to force Chef's git resource to use repository-specific deployment keys to clone/fetch from private Github repositories. The additional advantage of this method over the environment/script based ones is that since the key-path is encoded in the working-repo's config, it will use the same key on both initial clone and subsequent fetches/pushes.
    – Adam Franco
    Nov 19 '15 at 16:20






  • 1




    WOW! This is just great, didn't know about this. Thanks for the answer, quite helpful as well in puppet environments, to prevent the extra hassle to manage .ssh/config etc. +1!
    – gf_
    Jun 10 '16 at 18:36








  • 2




    If you encounter the following error fatal: transport 'ext' not allowed, you have to whitelist the ext protocol via the export GIT_ALLOW_PROTOCOL=ext. Basically, the git-remote-ext remote helper (which supports "ext::ssh example.com %S foo/repo" URLs) allows arbitrary command execution. This normally isn't ever a concern because user always sees and trusts the URL they pass to git. However git submodules, through the .gitmodules file, allow an attacker to request the client to fetch arbitrary git URLs. hackerone.com/reports/104465
    – Gomino
    May 13 at 17:21




















up vote
13
down vote













After my struggle with $GIT_SSH I would like to share what worked for me.



Through my examples I will assume you have your private key located at/home/user/.ssh/jenkins



Error to avoid: GIT_SSH value includes options



$ export GIT_SSH="ssh -i /home/user/.ssh/jenkins"


or whatever similar will fails, as git will try to execute the value as a file. For that reason, you have to create a script.



Working example of $GIT_SSH script /home/user/gssh.sh



The script will be invoked as follows:



$ $GIT_SSH [username@]host [-p <port>] <command>


Sample script working could look like:



#!/bin/sh
ssh -i /home/user/.ssh/jenkins $*


Note the $* at the end, it is important part of it.



Even safer alternative, which would prevent any possible conflict with anything in your default config file (plus explicitly mentioning the port to use) would be:



#!/bin/sh
ssh -i /home/user/.ssh/jenkins -F /dev/null -p 22 $*


Assuming the script is in /home/user/gssh.sh, you shall then:



$ export GIT_SSH=/home/user/gssh.sh


and all shall work.






share|improve this answer





















  • Thanks. Just note: use "$@" instead of $* for pass-thru arguments, as the former behaves correctly when arguments contain whitespace.
    – Piotr Findeisen
    Mar 31 '16 at 7:39










  • @PiotrFindeisen Thanks for your note. However, I do not understand it completely - in zsh it helps me to keep strings with space in one piece, but in bash not. Can you tell me more or point to some explanation? I do not want to add some modification blindly.
    – Jan Vlcinsky
    Mar 31 '16 at 10:33










  • You should remove the first half of your answer. No one's interested in a solution that doesn't work, and it's wasted reading that obfuscates the correct answer at the bottom, which works wonderfully.
    – Cerin
    Aug 3 at 16:47












  • @Cerin If you mean removing the "Error to avoid" I am going to keep it there. It shares common pitfall to avoid and it is very short. I am sure, someone would try optimizing the solution by providing all the things into variable (this happened to me), so I tried to shorten the path to success.
    – Jan Vlcinsky
    Aug 4 at 20:14


















up vote
9
down vote













Use custom host config in ~/.ssh/config, like this:



Host gitlab-as-thuc  
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa.thuc
IdentitiesOnly yes


then use your custom hostname like this:



git remote add thuc git@gitlab-as-thuc:your-repo.git  





share|improve this answer



















  • 1




    This is the answer I was looking for, as I have separate GitHub accounts for home and work. I just had to set Host work.github.com HostName github.com IdentityFile ~/.ssh/work, and then replace "github.com" by "work.github.com" whenever I clone a work repository. It still connects to "github.com", but using a non-default key pair.
    – Mikkel
    May 25 '16 at 17:06








  • 1




    The URL for details ("itblog.study.land/...") doesn't work any more :(
    – Carl Smotricz
    Sep 15 '17 at 8:10










  • @CarlSmotricz the original one was moved here: medium.com/@thucnc/…
    – thucnguyen
    Nov 27 at 7:13






  • 1




    FINALLY!!! This answer actually shows how you can utilize what you put in the ~/.ssh/config file. Every other answer misses how you can set the host when you add the origin, which automatically allows git to use the correct key file. THANK YOU!!
    – BrianVPS
    Dec 4 at 15:17


















up vote
5
down vote













You can just use ssh-ident instead of creating your own wrapper.



You can read more at:
https://github.com/ccontavalli/ssh-ident



It loads ssh keys on demand when first needed, once, even with multiple login sessions, xterms or NFS shared homes.



With a tiny config file, it can automatically load different keys and keep them separated in different agents (for agent forwarding) depending on what you need to do.






share|improve this answer






























    up vote
    4
    down vote













    I had a client that needed a separate github account. So I needed to use a separate key just for this one project.



    My solution was to add this to my .zshrc / .bashrc:



    alias infogit="GIT_SSH_COMMAND="ssh -i ~/.ssh/id_specialkey" git $@"


    Whenever I want to use git for that project I replace "infogit" with git:



    infogit commit -am "Some message" && infogit push


    For me, it's easier to remember.






    share|improve this answer




























      up vote
      2
      down vote













      My solution was this:



      create a script:



      #!/bin/bash
      KEY=dafault_key_to_be_used
      PORT=10022 #default port...
      for i in $@;do
      case $i in
      --port=*)
      PORT="${i:7}";;
      --key=*)KEY="${i:6}";;
      esac
      done
      export GIT_SSH_COMMAND="ssh -i $HOME/.ssh/${KEY} -p ${PORT}"
      echo Command: $GIT_SSH_COMMAND


      then when you have to change the var run:



      . ./thescript.sh [--port=] [--key=]


      Don't forget the extra dot!! this makes the script set the environments vars!! --key and --port are optional.






      share|improve this answer




























        up vote
        2
        down vote













        So I set the GIT_SSH env variable to $HOME/bin/git-ssh.



        In order to support having my repo configuration dictate which ssh identity to use, my ~/bin/git-ssh file is this:



        #!/bin/sh
        ssh -i $(git config --get ssh.identity) -F /dev/null -p 22 $*


        Then I have a global git config setting:



        $ git config --global ssh.identity ~/.ssh/default_id_rsa


        And within any git repository I can just set a local ssh.identity git config value:



        $ git config --local ssh.identity ~/.ssh/any_other_id_rsa


        Voila!



        If you can have a different email address for each identity, it gets even simpler, because you can just name your keys after your email addresses and then have the git config's user.email drive the key selection in a ~/bin/git-ssh like this:



        #!/bin/sh
        ssh -i $HOME/.ssh/$(git config --get user.email) -F /dev/null -p 22 $*





        share|improve this answer






























          up vote
          1
          down vote













          Generally, you want to use ~/.ssh/config for this. Simply pair server addresses with the keys you want to use for them as follows:



          Host github.com
          IdentityFile ~/.ssh/id_rsa.github
          Host heroku.com
          IdentityFile ~/.ssh/id_rsa.heroku
          Host *
          IdentityFile ~/.ssh/id_rsa


          Host * denotes any server, so I use it to set ~/.ssh/id_rsa as the default key to use.






          share|improve this answer




























            up vote
            1
            down vote













            I build on @shellholic and this SO thread with a few teaks. I use GitHub as an example and assume that you have a private key in ~/.ssh/github (otherwise, see this SO thread) and that you added the public key to your GitHub profile (otherwise see GitHub's help).



            If needed, create a new SSH config file at ~/.ssh/config and change permissions to 400



            touch ~/.ssh/config
            chmod 600 ~/.ssh/config


            Add this to the ~/.ssh/config file:



            Host github.com
            IdentityFile ~/.ssh/github
            IdentitiesOnly yes


            If you already have a remote set up, you may want to delete it, otherwise you may still be prompted for username and password:



            git remote rm origin


            Then add a remote to the git repository, and notice the colon before the user name:



            git remote add origin git@github.com:user_name/repo_name.git


            And then git commands work normally, e.g.:



            git push origin master
            git pull origin


            @HeyWatchThis on this SO thread suggested adding IdentitiesOnly yes to prevent the SSH default behavior of sending the identity file matching the default filename for each protocol. See that thread for more information and references.






            share|improve this answer





















            • This was my mistake: "If you already have a remote set up...". Thanks a lot!!!
              – Allan Andrade
              Oct 4 at 17:43


















            up vote
            0
            down vote













            I'm using git version 2.16 and I don't need a single piece of script not even a config or modified commands.




            • Just copied my private key to .ssh/id_rsa

            • set permissions to 600


            And git reads to key automatically. I doesn't ask anything and it doesn't throw an error. Just works fine.






            share|improve this answer





















            • Did you notice that the question is about “a system with multiple private keys in the ~/.ssh directory”?
              – Scott
              Jun 6 at 5:16


















            up vote
            0
            down vote













            Just use ssh-agent and ssh-add commands.



            # create a agent
            ssh-agent

            # add your default key
            ssh-add ~/.ssh/id_rsa

            # add your second key
            ssh-add ~/.ssh/<your key name>


            After execute above commands, you can use both key as same time.
            Just type



            git clone git@github.com:<yourname>/<your-repo>.git


            to connect your repository.



            You need to execute above command after you reboot your machine.



            English is not my native language; please excuse typing errors.






            share|improve this answer























              Your Answer








              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "3"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f232373%2fhow-to-tell-git-which-private-key-to-use%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              15 Answers
              15






              active

              oldest

              votes








              15 Answers
              15






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              558
              down vote



              accepted










              In ~/.ssh/config, add:



              host github.com
              HostName github.com
              IdentityFile ~/.ssh/id_rsa_github
              User git


              Now you can do git clone git@github.com:username/repo.git.



              NOTE: Verify that the permissions on IdentityFile are 400.SSH will reject, in a not clearly explicit manner, SSH keys that are too readable. It will just look like a credential rejection. The solution, in this case, is:



              chmod 400 ~/.ssh/id_rsa_github





              share|improve this answer



















              • 76




                What if you need to connect to the same host with different keys?
                – Valentin Klinghammer
                Nov 30 '12 at 11:24






              • 6




                @Quelltextfabrik - you can add another section with a different Host: nerderati.com/2011/03/…
                – Ben Challenor
                Dec 4 '12 at 14:17






              • 1




                @Cliff Nop, in my manpage: "HostName: Specifies the real host name to log into. This can be used to specify nicknames or abbreviations for hosts." My ssh version is openssh-6.7p1.
                – Grissiom
                Jan 7 '15 at 2:17






              • 1




                @Grissiom That's exactly what it says. But you seem to understand the meaning backwards. Host (or Match) is required. To create a host nickname you place the nickname in the Host line and the real hostname in the HostName line. Examples: saltycrane.com/blog/2008/11/…
                – Cliff
                Jan 8 '15 at 3:55






              • 7




                If the config file is new, don't forget to do chmod 600 ~/.ssh/config
                – elysch
                Mar 15 '16 at 23:02















              up vote
              558
              down vote



              accepted










              In ~/.ssh/config, add:



              host github.com
              HostName github.com
              IdentityFile ~/.ssh/id_rsa_github
              User git


              Now you can do git clone git@github.com:username/repo.git.



              NOTE: Verify that the permissions on IdentityFile are 400.SSH will reject, in a not clearly explicit manner, SSH keys that are too readable. It will just look like a credential rejection. The solution, in this case, is:



              chmod 400 ~/.ssh/id_rsa_github





              share|improve this answer



















              • 76




                What if you need to connect to the same host with different keys?
                – Valentin Klinghammer
                Nov 30 '12 at 11:24






              • 6




                @Quelltextfabrik - you can add another section with a different Host: nerderati.com/2011/03/…
                – Ben Challenor
                Dec 4 '12 at 14:17






              • 1




                @Cliff Nop, in my manpage: "HostName: Specifies the real host name to log into. This can be used to specify nicknames or abbreviations for hosts." My ssh version is openssh-6.7p1.
                – Grissiom
                Jan 7 '15 at 2:17






              • 1




                @Grissiom That's exactly what it says. But you seem to understand the meaning backwards. Host (or Match) is required. To create a host nickname you place the nickname in the Host line and the real hostname in the HostName line. Examples: saltycrane.com/blog/2008/11/…
                – Cliff
                Jan 8 '15 at 3:55






              • 7




                If the config file is new, don't forget to do chmod 600 ~/.ssh/config
                – elysch
                Mar 15 '16 at 23:02













              up vote
              558
              down vote



              accepted







              up vote
              558
              down vote



              accepted






              In ~/.ssh/config, add:



              host github.com
              HostName github.com
              IdentityFile ~/.ssh/id_rsa_github
              User git


              Now you can do git clone git@github.com:username/repo.git.



              NOTE: Verify that the permissions on IdentityFile are 400.SSH will reject, in a not clearly explicit manner, SSH keys that are too readable. It will just look like a credential rejection. The solution, in this case, is:



              chmod 400 ~/.ssh/id_rsa_github





              share|improve this answer














              In ~/.ssh/config, add:



              host github.com
              HostName github.com
              IdentityFile ~/.ssh/id_rsa_github
              User git


              Now you can do git clone git@github.com:username/repo.git.



              NOTE: Verify that the permissions on IdentityFile are 400.SSH will reject, in a not clearly explicit manner, SSH keys that are too readable. It will just look like a credential rejection. The solution, in this case, is:



              chmod 400 ~/.ssh/id_rsa_github






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Oct 7 '15 at 8:31









              silviot

              28849




              28849










              answered Jan 12 '11 at 19:36









              shellholic

              6,3971118




              6,3971118








              • 76




                What if you need to connect to the same host with different keys?
                – Valentin Klinghammer
                Nov 30 '12 at 11:24






              • 6




                @Quelltextfabrik - you can add another section with a different Host: nerderati.com/2011/03/…
                – Ben Challenor
                Dec 4 '12 at 14:17






              • 1




                @Cliff Nop, in my manpage: "HostName: Specifies the real host name to log into. This can be used to specify nicknames or abbreviations for hosts." My ssh version is openssh-6.7p1.
                – Grissiom
                Jan 7 '15 at 2:17






              • 1




                @Grissiom That's exactly what it says. But you seem to understand the meaning backwards. Host (or Match) is required. To create a host nickname you place the nickname in the Host line and the real hostname in the HostName line. Examples: saltycrane.com/blog/2008/11/…
                – Cliff
                Jan 8 '15 at 3:55






              • 7




                If the config file is new, don't forget to do chmod 600 ~/.ssh/config
                – elysch
                Mar 15 '16 at 23:02














              • 76




                What if you need to connect to the same host with different keys?
                – Valentin Klinghammer
                Nov 30 '12 at 11:24






              • 6




                @Quelltextfabrik - you can add another section with a different Host: nerderati.com/2011/03/…
                – Ben Challenor
                Dec 4 '12 at 14:17






              • 1




                @Cliff Nop, in my manpage: "HostName: Specifies the real host name to log into. This can be used to specify nicknames or abbreviations for hosts." My ssh version is openssh-6.7p1.
                – Grissiom
                Jan 7 '15 at 2:17






              • 1




                @Grissiom That's exactly what it says. But you seem to understand the meaning backwards. Host (or Match) is required. To create a host nickname you place the nickname in the Host line and the real hostname in the HostName line. Examples: saltycrane.com/blog/2008/11/…
                – Cliff
                Jan 8 '15 at 3:55






              • 7




                If the config file is new, don't forget to do chmod 600 ~/.ssh/config
                – elysch
                Mar 15 '16 at 23:02








              76




              76




              What if you need to connect to the same host with different keys?
              – Valentin Klinghammer
              Nov 30 '12 at 11:24




              What if you need to connect to the same host with different keys?
              – Valentin Klinghammer
              Nov 30 '12 at 11:24




              6




              6




              @Quelltextfabrik - you can add another section with a different Host: nerderati.com/2011/03/…
              – Ben Challenor
              Dec 4 '12 at 14:17




              @Quelltextfabrik - you can add another section with a different Host: nerderati.com/2011/03/…
              – Ben Challenor
              Dec 4 '12 at 14:17




              1




              1




              @Cliff Nop, in my manpage: "HostName: Specifies the real host name to log into. This can be used to specify nicknames or abbreviations for hosts." My ssh version is openssh-6.7p1.
              – Grissiom
              Jan 7 '15 at 2:17




              @Cliff Nop, in my manpage: "HostName: Specifies the real host name to log into. This can be used to specify nicknames or abbreviations for hosts." My ssh version is openssh-6.7p1.
              – Grissiom
              Jan 7 '15 at 2:17




              1




              1




              @Grissiom That's exactly what it says. But you seem to understand the meaning backwards. Host (or Match) is required. To create a host nickname you place the nickname in the Host line and the real hostname in the HostName line. Examples: saltycrane.com/blog/2008/11/…
              – Cliff
              Jan 8 '15 at 3:55




              @Grissiom That's exactly what it says. But you seem to understand the meaning backwards. Host (or Match) is required. To create a host nickname you place the nickname in the Host line and the real hostname in the HostName line. Examples: saltycrane.com/blog/2008/11/…
              – Cliff
              Jan 8 '15 at 3:55




              7




              7




              If the config file is new, don't forget to do chmod 600 ~/.ssh/config
              – elysch
              Mar 15 '16 at 23:02




              If the config file is new, don't forget to do chmod 600 ~/.ssh/config
              – elysch
              Mar 15 '16 at 23:02












              up vote
              244
              down vote













              Environment variable GIT_SSH_COMMAND:



              From Git version 2.3.0, you can use the environment variable GIT_SSH_COMMAND like this:



              GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example" git clone example


              Note that -i can sometimes be overridden by your config file, in which case, you should give SSH an empty config file, like this:



              GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example -F /dev/null" git clone example


              Configuration core.sshCommand:



              From Git version 2.10.0, you can configure this per repo or globally, so you don't have to set the environment variable any more!



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





              share|improve this answer



















              • 1




                I had to export the shell variable to an environment variable to make this work, i.e. export GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example", then git clone example
                – Abdull
                Dec 1 '15 at 13:46








              • 6




                @Abdull In Bash, doing the assignment on the same line as the command exports the environment variable for just that command. Try it: example=hello /usr/bin/env | grep example.
                – Flimm
                Jan 8 '16 at 9:50






              • 3




                things have become even better: as of Git 2.10, you can store the command in your Git configuration: stackoverflow.com/a/38474220/520162
                – eckes
                Oct 21 '16 at 7:57






              • 1




                @Noitidart /dev/null is only a valid filename in UNIX-like operating systems, it doesn't work on Windows.
                – Flimm
                Mar 7 '17 at 8:19






              • 1




                If you need multiple keys, the -i parameter can be repeated, and ssh will try each key in turn. git config core.sshcommand "ssh -i /path/to/keyA -i /path/to/keyB". This lets git use different keys with different remote hosts.
                – Mark
                Jun 23 '17 at 3:44















              up vote
              244
              down vote













              Environment variable GIT_SSH_COMMAND:



              From Git version 2.3.0, you can use the environment variable GIT_SSH_COMMAND like this:



              GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example" git clone example


              Note that -i can sometimes be overridden by your config file, in which case, you should give SSH an empty config file, like this:



              GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example -F /dev/null" git clone example


              Configuration core.sshCommand:



              From Git version 2.10.0, you can configure this per repo or globally, so you don't have to set the environment variable any more!



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





              share|improve this answer



















              • 1




                I had to export the shell variable to an environment variable to make this work, i.e. export GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example", then git clone example
                – Abdull
                Dec 1 '15 at 13:46








              • 6




                @Abdull In Bash, doing the assignment on the same line as the command exports the environment variable for just that command. Try it: example=hello /usr/bin/env | grep example.
                – Flimm
                Jan 8 '16 at 9:50






              • 3




                things have become even better: as of Git 2.10, you can store the command in your Git configuration: stackoverflow.com/a/38474220/520162
                – eckes
                Oct 21 '16 at 7:57






              • 1




                @Noitidart /dev/null is only a valid filename in UNIX-like operating systems, it doesn't work on Windows.
                – Flimm
                Mar 7 '17 at 8:19






              • 1




                If you need multiple keys, the -i parameter can be repeated, and ssh will try each key in turn. git config core.sshcommand "ssh -i /path/to/keyA -i /path/to/keyB". This lets git use different keys with different remote hosts.
                – Mark
                Jun 23 '17 at 3:44













              up vote
              244
              down vote










              up vote
              244
              down vote









              Environment variable GIT_SSH_COMMAND:



              From Git version 2.3.0, you can use the environment variable GIT_SSH_COMMAND like this:



              GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example" git clone example


              Note that -i can sometimes be overridden by your config file, in which case, you should give SSH an empty config file, like this:



              GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example -F /dev/null" git clone example


              Configuration core.sshCommand:



              From Git version 2.10.0, you can configure this per repo or globally, so you don't have to set the environment variable any more!



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





              share|improve this answer














              Environment variable GIT_SSH_COMMAND:



              From Git version 2.3.0, you can use the environment variable GIT_SSH_COMMAND like this:



              GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example" git clone example


              Note that -i can sometimes be overridden by your config file, in which case, you should give SSH an empty config file, like this:



              GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example -F /dev/null" git clone example


              Configuration core.sshCommand:



              From Git version 2.10.0, you can configure this per repo or globally, so you don't have to set the environment variable any more!



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






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Oct 28 '16 at 11:30

























              answered May 8 '15 at 9:43









              Flimm

              4,37722032




              4,37722032








              • 1




                I had to export the shell variable to an environment variable to make this work, i.e. export GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example", then git clone example
                – Abdull
                Dec 1 '15 at 13:46








              • 6




                @Abdull In Bash, doing the assignment on the same line as the command exports the environment variable for just that command. Try it: example=hello /usr/bin/env | grep example.
                – Flimm
                Jan 8 '16 at 9:50






              • 3




                things have become even better: as of Git 2.10, you can store the command in your Git configuration: stackoverflow.com/a/38474220/520162
                – eckes
                Oct 21 '16 at 7:57






              • 1




                @Noitidart /dev/null is only a valid filename in UNIX-like operating systems, it doesn't work on Windows.
                – Flimm
                Mar 7 '17 at 8:19






              • 1




                If you need multiple keys, the -i parameter can be repeated, and ssh will try each key in turn. git config core.sshcommand "ssh -i /path/to/keyA -i /path/to/keyB". This lets git use different keys with different remote hosts.
                – Mark
                Jun 23 '17 at 3:44














              • 1




                I had to export the shell variable to an environment variable to make this work, i.e. export GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example", then git clone example
                – Abdull
                Dec 1 '15 at 13:46








              • 6




                @Abdull In Bash, doing the assignment on the same line as the command exports the environment variable for just that command. Try it: example=hello /usr/bin/env | grep example.
                – Flimm
                Jan 8 '16 at 9:50






              • 3




                things have become even better: as of Git 2.10, you can store the command in your Git configuration: stackoverflow.com/a/38474220/520162
                – eckes
                Oct 21 '16 at 7:57






              • 1




                @Noitidart /dev/null is only a valid filename in UNIX-like operating systems, it doesn't work on Windows.
                – Flimm
                Mar 7 '17 at 8:19






              • 1




                If you need multiple keys, the -i parameter can be repeated, and ssh will try each key in turn. git config core.sshcommand "ssh -i /path/to/keyA -i /path/to/keyB". This lets git use different keys with different remote hosts.
                – Mark
                Jun 23 '17 at 3:44








              1




              1




              I had to export the shell variable to an environment variable to make this work, i.e. export GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example", then git clone example
              – Abdull
              Dec 1 '15 at 13:46






              I had to export the shell variable to an environment variable to make this work, i.e. export GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example", then git clone example
              – Abdull
              Dec 1 '15 at 13:46






              6




              6




              @Abdull In Bash, doing the assignment on the same line as the command exports the environment variable for just that command. Try it: example=hello /usr/bin/env | grep example.
              – Flimm
              Jan 8 '16 at 9:50




              @Abdull In Bash, doing the assignment on the same line as the command exports the environment variable for just that command. Try it: example=hello /usr/bin/env | grep example.
              – Flimm
              Jan 8 '16 at 9:50




              3




              3




              things have become even better: as of Git 2.10, you can store the command in your Git configuration: stackoverflow.com/a/38474220/520162
              – eckes
              Oct 21 '16 at 7:57




              things have become even better: as of Git 2.10, you can store the command in your Git configuration: stackoverflow.com/a/38474220/520162
              – eckes
              Oct 21 '16 at 7:57




              1




              1




              @Noitidart /dev/null is only a valid filename in UNIX-like operating systems, it doesn't work on Windows.
              – Flimm
              Mar 7 '17 at 8:19




              @Noitidart /dev/null is only a valid filename in UNIX-like operating systems, it doesn't work on Windows.
              – Flimm
              Mar 7 '17 at 8:19




              1




              1




              If you need multiple keys, the -i parameter can be repeated, and ssh will try each key in turn. git config core.sshcommand "ssh -i /path/to/keyA -i /path/to/keyB". This lets git use different keys with different remote hosts.
              – Mark
              Jun 23 '17 at 3:44




              If you need multiple keys, the -i parameter can be repeated, and ssh will try each key in turn. git config core.sshcommand "ssh -i /path/to/keyA -i /path/to/keyB". This lets git use different keys with different remote hosts.
              – Mark
              Jun 23 '17 at 3:44










              up vote
              73
              down vote













              There is no direct way to tell git which private key to use, because it relies on ssh for repository authentication. However, there are still a few ways to achieve your goal:



              Option 1: ssh-agent



              You can use ssh-agent to temporarily authorize your private key.



              For example:



              $ ssh-agent sh -c 'ssh-add ~/.ssh/id_rsa; git fetch user@host'


              Option 2: GIT_SSH_COMMAND



              Pass the ssh arguments by using the GIT_SSH_COMMAND environment variable
              (Git 2.3.0+).



              For example:



              $ GIT_SSH_COMMAND='ssh -i ~/.ssh/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no' 
              git clone user@host


              You can type this all on one line — ignore $ and leave out the .



              Option 3: GIT_SSH



              Pass the ssh arguments by using the GIT_SSH environment variable to specify alternate ssh binary.



              For example:



              $ echo 'ssh -i ~/.ssh/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no $*' > ssh
              $ chmod +x ssh
              $ GIT_TRACE=1 GIT_SSH='./ssh' git clone user@host


              Note: The above lines are shell (terminal) command lines which you should paste into your terminal. They will create a file named ssh, make it executable, and (indirectly) execute it.



              Note: GIT_SSH is available since v0.99.4 (2005).



              Option 4: ~/.ssh/config



              Use the ~/.ssh/config file as suggested in other answers in order to specify the location of your private key, e.g.



              Host github.com
              User git
              Hostname github.com
              IdentityFile ~/.ssh/id_rsa





              share|improve this answer



















              • 1




                // , What if your identity in ssh-agent is forwarded, though, as in this question? superuser.com/questions/971732/…
                – Nathan Basanese
                Sep 11 '15 at 18:06






              • 1




                I've allowed me to reformat this post: IMO this is by far the most comprehensive answer. In its original design, a quick scan suggested the post where describing a single complicated solution to the problem, so I missed it.
                – Alberto
                Jan 21 '16 at 10:01






              • 2




                $ ssh-agent sh -c 'ssh-add ~/.ssh/id_rsa; git fetch user@host' worked for me when nothing else would. Kudos.
                – Daniel Dewhurst
                Sep 11 '17 at 15:24










              • I had to use ~/.ssh/config method, env vars didn't work for me...
                – Greg Dubicki
                Sep 22 '17 at 7:53






              • 1




                GIT_SSH is available since v0.99.4 (August 2005), so basically since Git exists (April 2005).
                – Dominik
                Nov 17 '17 at 8:10















              up vote
              73
              down vote













              There is no direct way to tell git which private key to use, because it relies on ssh for repository authentication. However, there are still a few ways to achieve your goal:



              Option 1: ssh-agent



              You can use ssh-agent to temporarily authorize your private key.



              For example:



              $ ssh-agent sh -c 'ssh-add ~/.ssh/id_rsa; git fetch user@host'


              Option 2: GIT_SSH_COMMAND



              Pass the ssh arguments by using the GIT_SSH_COMMAND environment variable
              (Git 2.3.0+).



              For example:



              $ GIT_SSH_COMMAND='ssh -i ~/.ssh/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no' 
              git clone user@host


              You can type this all on one line — ignore $ and leave out the .



              Option 3: GIT_SSH



              Pass the ssh arguments by using the GIT_SSH environment variable to specify alternate ssh binary.



              For example:



              $ echo 'ssh -i ~/.ssh/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no $*' > ssh
              $ chmod +x ssh
              $ GIT_TRACE=1 GIT_SSH='./ssh' git clone user@host


              Note: The above lines are shell (terminal) command lines which you should paste into your terminal. They will create a file named ssh, make it executable, and (indirectly) execute it.



              Note: GIT_SSH is available since v0.99.4 (2005).



              Option 4: ~/.ssh/config



              Use the ~/.ssh/config file as suggested in other answers in order to specify the location of your private key, e.g.



              Host github.com
              User git
              Hostname github.com
              IdentityFile ~/.ssh/id_rsa





              share|improve this answer



















              • 1




                // , What if your identity in ssh-agent is forwarded, though, as in this question? superuser.com/questions/971732/…
                – Nathan Basanese
                Sep 11 '15 at 18:06






              • 1




                I've allowed me to reformat this post: IMO this is by far the most comprehensive answer. In its original design, a quick scan suggested the post where describing a single complicated solution to the problem, so I missed it.
                – Alberto
                Jan 21 '16 at 10:01






              • 2




                $ ssh-agent sh -c 'ssh-add ~/.ssh/id_rsa; git fetch user@host' worked for me when nothing else would. Kudos.
                – Daniel Dewhurst
                Sep 11 '17 at 15:24










              • I had to use ~/.ssh/config method, env vars didn't work for me...
                – Greg Dubicki
                Sep 22 '17 at 7:53






              • 1




                GIT_SSH is available since v0.99.4 (August 2005), so basically since Git exists (April 2005).
                – Dominik
                Nov 17 '17 at 8:10













              up vote
              73
              down vote










              up vote
              73
              down vote









              There is no direct way to tell git which private key to use, because it relies on ssh for repository authentication. However, there are still a few ways to achieve your goal:



              Option 1: ssh-agent



              You can use ssh-agent to temporarily authorize your private key.



              For example:



              $ ssh-agent sh -c 'ssh-add ~/.ssh/id_rsa; git fetch user@host'


              Option 2: GIT_SSH_COMMAND



              Pass the ssh arguments by using the GIT_SSH_COMMAND environment variable
              (Git 2.3.0+).



              For example:



              $ GIT_SSH_COMMAND='ssh -i ~/.ssh/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no' 
              git clone user@host


              You can type this all on one line — ignore $ and leave out the .



              Option 3: GIT_SSH



              Pass the ssh arguments by using the GIT_SSH environment variable to specify alternate ssh binary.



              For example:



              $ echo 'ssh -i ~/.ssh/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no $*' > ssh
              $ chmod +x ssh
              $ GIT_TRACE=1 GIT_SSH='./ssh' git clone user@host


              Note: The above lines are shell (terminal) command lines which you should paste into your terminal. They will create a file named ssh, make it executable, and (indirectly) execute it.



              Note: GIT_SSH is available since v0.99.4 (2005).



              Option 4: ~/.ssh/config



              Use the ~/.ssh/config file as suggested in other answers in order to specify the location of your private key, e.g.



              Host github.com
              User git
              Hostname github.com
              IdentityFile ~/.ssh/id_rsa





              share|improve this answer














              There is no direct way to tell git which private key to use, because it relies on ssh for repository authentication. However, there are still a few ways to achieve your goal:



              Option 1: ssh-agent



              You can use ssh-agent to temporarily authorize your private key.



              For example:



              $ ssh-agent sh -c 'ssh-add ~/.ssh/id_rsa; git fetch user@host'


              Option 2: GIT_SSH_COMMAND



              Pass the ssh arguments by using the GIT_SSH_COMMAND environment variable
              (Git 2.3.0+).



              For example:



              $ GIT_SSH_COMMAND='ssh -i ~/.ssh/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no' 
              git clone user@host


              You can type this all on one line — ignore $ and leave out the .



              Option 3: GIT_SSH



              Pass the ssh arguments by using the GIT_SSH environment variable to specify alternate ssh binary.



              For example:



              $ echo 'ssh -i ~/.ssh/id_rsa -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no $*' > ssh
              $ chmod +x ssh
              $ GIT_TRACE=1 GIT_SSH='./ssh' git clone user@host


              Note: The above lines are shell (terminal) command lines which you should paste into your terminal. They will create a file named ssh, make it executable, and (indirectly) execute it.



              Note: GIT_SSH is available since v0.99.4 (2005).



              Option 4: ~/.ssh/config



              Use the ~/.ssh/config file as suggested in other answers in order to specify the location of your private key, e.g.



              Host github.com
              User git
              Hostname github.com
              IdentityFile ~/.ssh/id_rsa






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 17 '17 at 14:13

























              answered Jan 23 '15 at 22:08









              kenorb

              10.7k1577111




              10.7k1577111








              • 1




                // , What if your identity in ssh-agent is forwarded, though, as in this question? superuser.com/questions/971732/…
                – Nathan Basanese
                Sep 11 '15 at 18:06






              • 1




                I've allowed me to reformat this post: IMO this is by far the most comprehensive answer. In its original design, a quick scan suggested the post where describing a single complicated solution to the problem, so I missed it.
                – Alberto
                Jan 21 '16 at 10:01






              • 2




                $ ssh-agent sh -c 'ssh-add ~/.ssh/id_rsa; git fetch user@host' worked for me when nothing else would. Kudos.
                – Daniel Dewhurst
                Sep 11 '17 at 15:24










              • I had to use ~/.ssh/config method, env vars didn't work for me...
                – Greg Dubicki
                Sep 22 '17 at 7:53






              • 1




                GIT_SSH is available since v0.99.4 (August 2005), so basically since Git exists (April 2005).
                – Dominik
                Nov 17 '17 at 8:10














              • 1




                // , What if your identity in ssh-agent is forwarded, though, as in this question? superuser.com/questions/971732/…
                – Nathan Basanese
                Sep 11 '15 at 18:06






              • 1




                I've allowed me to reformat this post: IMO this is by far the most comprehensive answer. In its original design, a quick scan suggested the post where describing a single complicated solution to the problem, so I missed it.
                – Alberto
                Jan 21 '16 at 10:01






              • 2




                $ ssh-agent sh -c 'ssh-add ~/.ssh/id_rsa; git fetch user@host' worked for me when nothing else would. Kudos.
                – Daniel Dewhurst
                Sep 11 '17 at 15:24










              • I had to use ~/.ssh/config method, env vars didn't work for me...
                – Greg Dubicki
                Sep 22 '17 at 7:53






              • 1




                GIT_SSH is available since v0.99.4 (August 2005), so basically since Git exists (April 2005).
                – Dominik
                Nov 17 '17 at 8:10








              1




              1




              // , What if your identity in ssh-agent is forwarded, though, as in this question? superuser.com/questions/971732/…
              – Nathan Basanese
              Sep 11 '15 at 18:06




              // , What if your identity in ssh-agent is forwarded, though, as in this question? superuser.com/questions/971732/…
              – Nathan Basanese
              Sep 11 '15 at 18:06




              1




              1




              I've allowed me to reformat this post: IMO this is by far the most comprehensive answer. In its original design, a quick scan suggested the post where describing a single complicated solution to the problem, so I missed it.
              – Alberto
              Jan 21 '16 at 10:01




              I've allowed me to reformat this post: IMO this is by far the most comprehensive answer. In its original design, a quick scan suggested the post where describing a single complicated solution to the problem, so I missed it.
              – Alberto
              Jan 21 '16 at 10:01




              2




              2




              $ ssh-agent sh -c 'ssh-add ~/.ssh/id_rsa; git fetch user@host' worked for me when nothing else would. Kudos.
              – Daniel Dewhurst
              Sep 11 '17 at 15:24




              $ ssh-agent sh -c 'ssh-add ~/.ssh/id_rsa; git fetch user@host' worked for me when nothing else would. Kudos.
              – Daniel Dewhurst
              Sep 11 '17 at 15:24












              I had to use ~/.ssh/config method, env vars didn't work for me...
              – Greg Dubicki
              Sep 22 '17 at 7:53




              I had to use ~/.ssh/config method, env vars didn't work for me...
              – Greg Dubicki
              Sep 22 '17 at 7:53




              1




              1




              GIT_SSH is available since v0.99.4 (August 2005), so basically since Git exists (April 2005).
              – Dominik
              Nov 17 '17 at 8:10




              GIT_SSH is available since v0.99.4 (August 2005), so basically since Git exists (April 2005).
              – Dominik
              Nov 17 '17 at 8:10










              up vote
              32
              down vote













              Write a script that calls ssh with the arguments you want, and put the filename of the script in $GIT_SSH. Or just put your configuration in ~/.ssh/config.






              share|improve this answer

















              • 1




                Another explanation of how to do this.
                – Sithsu
                May 12 '14 at 19:44








              • 1




                ~/.ssh/config Is the way to go.
                – hek2mgl
                May 8 '15 at 13:56










              • I work on a machine (A) from which I git push to a server (B) that only accepts ssh key authentication. While my ~/.ssh/config setup on (A) works perfectly fine when I work directly on that machine, it does not when I login from some other location (C). Using $GIT_SSH and a script solved this problem. Thanks!
                – bsumirak
                Dec 3 '15 at 17:28















              up vote
              32
              down vote













              Write a script that calls ssh with the arguments you want, and put the filename of the script in $GIT_SSH. Or just put your configuration in ~/.ssh/config.






              share|improve this answer

















              • 1




                Another explanation of how to do this.
                – Sithsu
                May 12 '14 at 19:44








              • 1




                ~/.ssh/config Is the way to go.
                – hek2mgl
                May 8 '15 at 13:56










              • I work on a machine (A) from which I git push to a server (B) that only accepts ssh key authentication. While my ~/.ssh/config setup on (A) works perfectly fine when I work directly on that machine, it does not when I login from some other location (C). Using $GIT_SSH and a script solved this problem. Thanks!
                – bsumirak
                Dec 3 '15 at 17:28













              up vote
              32
              down vote










              up vote
              32
              down vote









              Write a script that calls ssh with the arguments you want, and put the filename of the script in $GIT_SSH. Or just put your configuration in ~/.ssh/config.






              share|improve this answer












              Write a script that calls ssh with the arguments you want, and put the filename of the script in $GIT_SSH. Or just put your configuration in ~/.ssh/config.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Jan 12 '11 at 18:25









              Ignacio Vazquez-Abrams

              95.4k6150209




              95.4k6150209








              • 1




                Another explanation of how to do this.
                – Sithsu
                May 12 '14 at 19:44








              • 1




                ~/.ssh/config Is the way to go.
                – hek2mgl
                May 8 '15 at 13:56










              • I work on a machine (A) from which I git push to a server (B) that only accepts ssh key authentication. While my ~/.ssh/config setup on (A) works perfectly fine when I work directly on that machine, it does not when I login from some other location (C). Using $GIT_SSH and a script solved this problem. Thanks!
                – bsumirak
                Dec 3 '15 at 17:28














              • 1




                Another explanation of how to do this.
                – Sithsu
                May 12 '14 at 19:44








              • 1




                ~/.ssh/config Is the way to go.
                – hek2mgl
                May 8 '15 at 13:56










              • I work on a machine (A) from which I git push to a server (B) that only accepts ssh key authentication. While my ~/.ssh/config setup on (A) works perfectly fine when I work directly on that machine, it does not when I login from some other location (C). Using $GIT_SSH and a script solved this problem. Thanks!
                – bsumirak
                Dec 3 '15 at 17:28








              1




              1




              Another explanation of how to do this.
              – Sithsu
              May 12 '14 at 19:44






              Another explanation of how to do this.
              – Sithsu
              May 12 '14 at 19:44






              1




              1




              ~/.ssh/config Is the way to go.
              – hek2mgl
              May 8 '15 at 13:56




              ~/.ssh/config Is the way to go.
              – hek2mgl
              May 8 '15 at 13:56












              I work on a machine (A) from which I git push to a server (B) that only accepts ssh key authentication. While my ~/.ssh/config setup on (A) works perfectly fine when I work directly on that machine, it does not when I login from some other location (C). Using $GIT_SSH and a script solved this problem. Thanks!
              – bsumirak
              Dec 3 '15 at 17:28




              I work on a machine (A) from which I git push to a server (B) that only accepts ssh key authentication. While my ~/.ssh/config setup on (A) works perfectly fine when I work directly on that machine, it does not when I login from some other location (C). Using $GIT_SSH and a script solved this problem. Thanks!
              – bsumirak
              Dec 3 '15 at 17:28










              up vote
              15
              down vote













              If you do not want to have to specify environment variables every time you run git, do not want another wrapper script, do not/can not run ssh-agent(1), nor want to download another package just for this, use the git-remote-ext(1) external transport:



              $ git clone 'ext::ssh -i $HOME/.ssh/alternate_id git.example.com %S /path/to/repository.git'
              Cloning into 'repository'
              (...)
              $ cd repository
              $ git remote -v
              origin ext::ssh -i $HOME/.ssh/alternate_id git.example.com %S /path/to/repository.git (fetch)
              origin ext::ssh -i $HOME/.ssh/alternate_id git.example.com %S /path/to/repository.git (push)


              I consider this solution superior because:




              • It is repository/remote specific

              • Avoid wrapper script bloat

              • Do not need the SSH agent -- useful if you want unattended clones/push/pulls (e.g. in cron)

              • Definitely, no external tool needed






              share|improve this answer





















              • // , Excellent solution. I wonder, though, if this would allow one to specify an identity passed through using agent forwarding. Most of my keys are not local to the servers I am using them on. I asked about this here: superuser.com/questions/971732/…
                – Nathan Basanese
                Sep 11 '15 at 18:09










              • The answer deals only with a way of specifying arbitrary command lines to be used as git repositories. IMHO, you should try to sort out your issue using ssh alone first (e.g. "ssh host" should connect using the right key). I will try to provide more info on your other question, though.
                – flaviovs
                Sep 14 '15 at 16:34






              • 1




                This answer was exactly what I needed to force Chef's git resource to use repository-specific deployment keys to clone/fetch from private Github repositories. The additional advantage of this method over the environment/script based ones is that since the key-path is encoded in the working-repo's config, it will use the same key on both initial clone and subsequent fetches/pushes.
                – Adam Franco
                Nov 19 '15 at 16:20






              • 1




                WOW! This is just great, didn't know about this. Thanks for the answer, quite helpful as well in puppet environments, to prevent the extra hassle to manage .ssh/config etc. +1!
                – gf_
                Jun 10 '16 at 18:36








              • 2




                If you encounter the following error fatal: transport 'ext' not allowed, you have to whitelist the ext protocol via the export GIT_ALLOW_PROTOCOL=ext. Basically, the git-remote-ext remote helper (which supports "ext::ssh example.com %S foo/repo" URLs) allows arbitrary command execution. This normally isn't ever a concern because user always sees and trusts the URL they pass to git. However git submodules, through the .gitmodules file, allow an attacker to request the client to fetch arbitrary git URLs. hackerone.com/reports/104465
                – Gomino
                May 13 at 17:21

















              up vote
              15
              down vote













              If you do not want to have to specify environment variables every time you run git, do not want another wrapper script, do not/can not run ssh-agent(1), nor want to download another package just for this, use the git-remote-ext(1) external transport:



              $ git clone 'ext::ssh -i $HOME/.ssh/alternate_id git.example.com %S /path/to/repository.git'
              Cloning into 'repository'
              (...)
              $ cd repository
              $ git remote -v
              origin ext::ssh -i $HOME/.ssh/alternate_id git.example.com %S /path/to/repository.git (fetch)
              origin ext::ssh -i $HOME/.ssh/alternate_id git.example.com %S /path/to/repository.git (push)


              I consider this solution superior because:




              • It is repository/remote specific

              • Avoid wrapper script bloat

              • Do not need the SSH agent -- useful if you want unattended clones/push/pulls (e.g. in cron)

              • Definitely, no external tool needed






              share|improve this answer





















              • // , Excellent solution. I wonder, though, if this would allow one to specify an identity passed through using agent forwarding. Most of my keys are not local to the servers I am using them on. I asked about this here: superuser.com/questions/971732/…
                – Nathan Basanese
                Sep 11 '15 at 18:09










              • The answer deals only with a way of specifying arbitrary command lines to be used as git repositories. IMHO, you should try to sort out your issue using ssh alone first (e.g. "ssh host" should connect using the right key). I will try to provide more info on your other question, though.
                – flaviovs
                Sep 14 '15 at 16:34






              • 1




                This answer was exactly what I needed to force Chef's git resource to use repository-specific deployment keys to clone/fetch from private Github repositories. The additional advantage of this method over the environment/script based ones is that since the key-path is encoded in the working-repo's config, it will use the same key on both initial clone and subsequent fetches/pushes.
                – Adam Franco
                Nov 19 '15 at 16:20






              • 1




                WOW! This is just great, didn't know about this. Thanks for the answer, quite helpful as well in puppet environments, to prevent the extra hassle to manage .ssh/config etc. +1!
                – gf_
                Jun 10 '16 at 18:36








              • 2




                If you encounter the following error fatal: transport 'ext' not allowed, you have to whitelist the ext protocol via the export GIT_ALLOW_PROTOCOL=ext. Basically, the git-remote-ext remote helper (which supports "ext::ssh example.com %S foo/repo" URLs) allows arbitrary command execution. This normally isn't ever a concern because user always sees and trusts the URL they pass to git. However git submodules, through the .gitmodules file, allow an attacker to request the client to fetch arbitrary git URLs. hackerone.com/reports/104465
                – Gomino
                May 13 at 17:21















              up vote
              15
              down vote










              up vote
              15
              down vote









              If you do not want to have to specify environment variables every time you run git, do not want another wrapper script, do not/can not run ssh-agent(1), nor want to download another package just for this, use the git-remote-ext(1) external transport:



              $ git clone 'ext::ssh -i $HOME/.ssh/alternate_id git.example.com %S /path/to/repository.git'
              Cloning into 'repository'
              (...)
              $ cd repository
              $ git remote -v
              origin ext::ssh -i $HOME/.ssh/alternate_id git.example.com %S /path/to/repository.git (fetch)
              origin ext::ssh -i $HOME/.ssh/alternate_id git.example.com %S /path/to/repository.git (push)


              I consider this solution superior because:




              • It is repository/remote specific

              • Avoid wrapper script bloat

              • Do not need the SSH agent -- useful if you want unattended clones/push/pulls (e.g. in cron)

              • Definitely, no external tool needed






              share|improve this answer












              If you do not want to have to specify environment variables every time you run git, do not want another wrapper script, do not/can not run ssh-agent(1), nor want to download another package just for this, use the git-remote-ext(1) external transport:



              $ git clone 'ext::ssh -i $HOME/.ssh/alternate_id git.example.com %S /path/to/repository.git'
              Cloning into 'repository'
              (...)
              $ cd repository
              $ git remote -v
              origin ext::ssh -i $HOME/.ssh/alternate_id git.example.com %S /path/to/repository.git (fetch)
              origin ext::ssh -i $HOME/.ssh/alternate_id git.example.com %S /path/to/repository.git (push)


              I consider this solution superior because:




              • It is repository/remote specific

              • Avoid wrapper script bloat

              • Do not need the SSH agent -- useful if you want unattended clones/push/pulls (e.g. in cron)

              • Definitely, no external tool needed







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Jul 21 '15 at 19:44









              flaviovs

              16915




              16915












              • // , Excellent solution. I wonder, though, if this would allow one to specify an identity passed through using agent forwarding. Most of my keys are not local to the servers I am using them on. I asked about this here: superuser.com/questions/971732/…
                – Nathan Basanese
                Sep 11 '15 at 18:09










              • The answer deals only with a way of specifying arbitrary command lines to be used as git repositories. IMHO, you should try to sort out your issue using ssh alone first (e.g. "ssh host" should connect using the right key). I will try to provide more info on your other question, though.
                – flaviovs
                Sep 14 '15 at 16:34






              • 1




                This answer was exactly what I needed to force Chef's git resource to use repository-specific deployment keys to clone/fetch from private Github repositories. The additional advantage of this method over the environment/script based ones is that since the key-path is encoded in the working-repo's config, it will use the same key on both initial clone and subsequent fetches/pushes.
                – Adam Franco
                Nov 19 '15 at 16:20






              • 1




                WOW! This is just great, didn't know about this. Thanks for the answer, quite helpful as well in puppet environments, to prevent the extra hassle to manage .ssh/config etc. +1!
                – gf_
                Jun 10 '16 at 18:36








              • 2




                If you encounter the following error fatal: transport 'ext' not allowed, you have to whitelist the ext protocol via the export GIT_ALLOW_PROTOCOL=ext. Basically, the git-remote-ext remote helper (which supports "ext::ssh example.com %S foo/repo" URLs) allows arbitrary command execution. This normally isn't ever a concern because user always sees and trusts the URL they pass to git. However git submodules, through the .gitmodules file, allow an attacker to request the client to fetch arbitrary git URLs. hackerone.com/reports/104465
                – Gomino
                May 13 at 17:21




















              • // , Excellent solution. I wonder, though, if this would allow one to specify an identity passed through using agent forwarding. Most of my keys are not local to the servers I am using them on. I asked about this here: superuser.com/questions/971732/…
                – Nathan Basanese
                Sep 11 '15 at 18:09










              • The answer deals only with a way of specifying arbitrary command lines to be used as git repositories. IMHO, you should try to sort out your issue using ssh alone first (e.g. "ssh host" should connect using the right key). I will try to provide more info on your other question, though.
                – flaviovs
                Sep 14 '15 at 16:34






              • 1




                This answer was exactly what I needed to force Chef's git resource to use repository-specific deployment keys to clone/fetch from private Github repositories. The additional advantage of this method over the environment/script based ones is that since the key-path is encoded in the working-repo's config, it will use the same key on both initial clone and subsequent fetches/pushes.
                – Adam Franco
                Nov 19 '15 at 16:20






              • 1




                WOW! This is just great, didn't know about this. Thanks for the answer, quite helpful as well in puppet environments, to prevent the extra hassle to manage .ssh/config etc. +1!
                – gf_
                Jun 10 '16 at 18:36








              • 2




                If you encounter the following error fatal: transport 'ext' not allowed, you have to whitelist the ext protocol via the export GIT_ALLOW_PROTOCOL=ext. Basically, the git-remote-ext remote helper (which supports "ext::ssh example.com %S foo/repo" URLs) allows arbitrary command execution. This normally isn't ever a concern because user always sees and trusts the URL they pass to git. However git submodules, through the .gitmodules file, allow an attacker to request the client to fetch arbitrary git URLs. hackerone.com/reports/104465
                – Gomino
                May 13 at 17:21


















              // , Excellent solution. I wonder, though, if this would allow one to specify an identity passed through using agent forwarding. Most of my keys are not local to the servers I am using them on. I asked about this here: superuser.com/questions/971732/…
              – Nathan Basanese
              Sep 11 '15 at 18:09




              // , Excellent solution. I wonder, though, if this would allow one to specify an identity passed through using agent forwarding. Most of my keys are not local to the servers I am using them on. I asked about this here: superuser.com/questions/971732/…
              – Nathan Basanese
              Sep 11 '15 at 18:09












              The answer deals only with a way of specifying arbitrary command lines to be used as git repositories. IMHO, you should try to sort out your issue using ssh alone first (e.g. "ssh host" should connect using the right key). I will try to provide more info on your other question, though.
              – flaviovs
              Sep 14 '15 at 16:34




              The answer deals only with a way of specifying arbitrary command lines to be used as git repositories. IMHO, you should try to sort out your issue using ssh alone first (e.g. "ssh host" should connect using the right key). I will try to provide more info on your other question, though.
              – flaviovs
              Sep 14 '15 at 16:34




              1




              1




              This answer was exactly what I needed to force Chef's git resource to use repository-specific deployment keys to clone/fetch from private Github repositories. The additional advantage of this method over the environment/script based ones is that since the key-path is encoded in the working-repo's config, it will use the same key on both initial clone and subsequent fetches/pushes.
              – Adam Franco
              Nov 19 '15 at 16:20




              This answer was exactly what I needed to force Chef's git resource to use repository-specific deployment keys to clone/fetch from private Github repositories. The additional advantage of this method over the environment/script based ones is that since the key-path is encoded in the working-repo's config, it will use the same key on both initial clone and subsequent fetches/pushes.
              – Adam Franco
              Nov 19 '15 at 16:20




              1




              1




              WOW! This is just great, didn't know about this. Thanks for the answer, quite helpful as well in puppet environments, to prevent the extra hassle to manage .ssh/config etc. +1!
              – gf_
              Jun 10 '16 at 18:36






              WOW! This is just great, didn't know about this. Thanks for the answer, quite helpful as well in puppet environments, to prevent the extra hassle to manage .ssh/config etc. +1!
              – gf_
              Jun 10 '16 at 18:36






              2




              2




              If you encounter the following error fatal: transport 'ext' not allowed, you have to whitelist the ext protocol via the export GIT_ALLOW_PROTOCOL=ext. Basically, the git-remote-ext remote helper (which supports "ext::ssh example.com %S foo/repo" URLs) allows arbitrary command execution. This normally isn't ever a concern because user always sees and trusts the URL they pass to git. However git submodules, through the .gitmodules file, allow an attacker to request the client to fetch arbitrary git URLs. hackerone.com/reports/104465
              – Gomino
              May 13 at 17:21






              If you encounter the following error fatal: transport 'ext' not allowed, you have to whitelist the ext protocol via the export GIT_ALLOW_PROTOCOL=ext. Basically, the git-remote-ext remote helper (which supports "ext::ssh example.com %S foo/repo" URLs) allows arbitrary command execution. This normally isn't ever a concern because user always sees and trusts the URL they pass to git. However git submodules, through the .gitmodules file, allow an attacker to request the client to fetch arbitrary git URLs. hackerone.com/reports/104465
              – Gomino
              May 13 at 17:21












              up vote
              13
              down vote













              After my struggle with $GIT_SSH I would like to share what worked for me.



              Through my examples I will assume you have your private key located at/home/user/.ssh/jenkins



              Error to avoid: GIT_SSH value includes options



              $ export GIT_SSH="ssh -i /home/user/.ssh/jenkins"


              or whatever similar will fails, as git will try to execute the value as a file. For that reason, you have to create a script.



              Working example of $GIT_SSH script /home/user/gssh.sh



              The script will be invoked as follows:



              $ $GIT_SSH [username@]host [-p <port>] <command>


              Sample script working could look like:



              #!/bin/sh
              ssh -i /home/user/.ssh/jenkins $*


              Note the $* at the end, it is important part of it.



              Even safer alternative, which would prevent any possible conflict with anything in your default config file (plus explicitly mentioning the port to use) would be:



              #!/bin/sh
              ssh -i /home/user/.ssh/jenkins -F /dev/null -p 22 $*


              Assuming the script is in /home/user/gssh.sh, you shall then:



              $ export GIT_SSH=/home/user/gssh.sh


              and all shall work.






              share|improve this answer





















              • Thanks. Just note: use "$@" instead of $* for pass-thru arguments, as the former behaves correctly when arguments contain whitespace.
                – Piotr Findeisen
                Mar 31 '16 at 7:39










              • @PiotrFindeisen Thanks for your note. However, I do not understand it completely - in zsh it helps me to keep strings with space in one piece, but in bash not. Can you tell me more or point to some explanation? I do not want to add some modification blindly.
                – Jan Vlcinsky
                Mar 31 '16 at 10:33










              • You should remove the first half of your answer. No one's interested in a solution that doesn't work, and it's wasted reading that obfuscates the correct answer at the bottom, which works wonderfully.
                – Cerin
                Aug 3 at 16:47












              • @Cerin If you mean removing the "Error to avoid" I am going to keep it there. It shares common pitfall to avoid and it is very short. I am sure, someone would try optimizing the solution by providing all the things into variable (this happened to me), so I tried to shorten the path to success.
                – Jan Vlcinsky
                Aug 4 at 20:14















              up vote
              13
              down vote













              After my struggle with $GIT_SSH I would like to share what worked for me.



              Through my examples I will assume you have your private key located at/home/user/.ssh/jenkins



              Error to avoid: GIT_SSH value includes options



              $ export GIT_SSH="ssh -i /home/user/.ssh/jenkins"


              or whatever similar will fails, as git will try to execute the value as a file. For that reason, you have to create a script.



              Working example of $GIT_SSH script /home/user/gssh.sh



              The script will be invoked as follows:



              $ $GIT_SSH [username@]host [-p <port>] <command>


              Sample script working could look like:



              #!/bin/sh
              ssh -i /home/user/.ssh/jenkins $*


              Note the $* at the end, it is important part of it.



              Even safer alternative, which would prevent any possible conflict with anything in your default config file (plus explicitly mentioning the port to use) would be:



              #!/bin/sh
              ssh -i /home/user/.ssh/jenkins -F /dev/null -p 22 $*


              Assuming the script is in /home/user/gssh.sh, you shall then:



              $ export GIT_SSH=/home/user/gssh.sh


              and all shall work.






              share|improve this answer





















              • Thanks. Just note: use "$@" instead of $* for pass-thru arguments, as the former behaves correctly when arguments contain whitespace.
                – Piotr Findeisen
                Mar 31 '16 at 7:39










              • @PiotrFindeisen Thanks for your note. However, I do not understand it completely - in zsh it helps me to keep strings with space in one piece, but in bash not. Can you tell me more or point to some explanation? I do not want to add some modification blindly.
                – Jan Vlcinsky
                Mar 31 '16 at 10:33










              • You should remove the first half of your answer. No one's interested in a solution that doesn't work, and it's wasted reading that obfuscates the correct answer at the bottom, which works wonderfully.
                – Cerin
                Aug 3 at 16:47












              • @Cerin If you mean removing the "Error to avoid" I am going to keep it there. It shares common pitfall to avoid and it is very short. I am sure, someone would try optimizing the solution by providing all the things into variable (this happened to me), so I tried to shorten the path to success.
                – Jan Vlcinsky
                Aug 4 at 20:14













              up vote
              13
              down vote










              up vote
              13
              down vote









              After my struggle with $GIT_SSH I would like to share what worked for me.



              Through my examples I will assume you have your private key located at/home/user/.ssh/jenkins



              Error to avoid: GIT_SSH value includes options



              $ export GIT_SSH="ssh -i /home/user/.ssh/jenkins"


              or whatever similar will fails, as git will try to execute the value as a file. For that reason, you have to create a script.



              Working example of $GIT_SSH script /home/user/gssh.sh



              The script will be invoked as follows:



              $ $GIT_SSH [username@]host [-p <port>] <command>


              Sample script working could look like:



              #!/bin/sh
              ssh -i /home/user/.ssh/jenkins $*


              Note the $* at the end, it is important part of it.



              Even safer alternative, which would prevent any possible conflict with anything in your default config file (plus explicitly mentioning the port to use) would be:



              #!/bin/sh
              ssh -i /home/user/.ssh/jenkins -F /dev/null -p 22 $*


              Assuming the script is in /home/user/gssh.sh, you shall then:



              $ export GIT_SSH=/home/user/gssh.sh


              and all shall work.






              share|improve this answer












              After my struggle with $GIT_SSH I would like to share what worked for me.



              Through my examples I will assume you have your private key located at/home/user/.ssh/jenkins



              Error to avoid: GIT_SSH value includes options



              $ export GIT_SSH="ssh -i /home/user/.ssh/jenkins"


              or whatever similar will fails, as git will try to execute the value as a file. For that reason, you have to create a script.



              Working example of $GIT_SSH script /home/user/gssh.sh



              The script will be invoked as follows:



              $ $GIT_SSH [username@]host [-p <port>] <command>


              Sample script working could look like:



              #!/bin/sh
              ssh -i /home/user/.ssh/jenkins $*


              Note the $* at the end, it is important part of it.



              Even safer alternative, which would prevent any possible conflict with anything in your default config file (plus explicitly mentioning the port to use) would be:



              #!/bin/sh
              ssh -i /home/user/.ssh/jenkins -F /dev/null -p 22 $*


              Assuming the script is in /home/user/gssh.sh, you shall then:



              $ export GIT_SSH=/home/user/gssh.sh


              and all shall work.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered May 28 '15 at 17:09









              Jan Vlcinsky

              32628




              32628












              • Thanks. Just note: use "$@" instead of $* for pass-thru arguments, as the former behaves correctly when arguments contain whitespace.
                – Piotr Findeisen
                Mar 31 '16 at 7:39










              • @PiotrFindeisen Thanks for your note. However, I do not understand it completely - in zsh it helps me to keep strings with space in one piece, but in bash not. Can you tell me more or point to some explanation? I do not want to add some modification blindly.
                – Jan Vlcinsky
                Mar 31 '16 at 10:33










              • You should remove the first half of your answer. No one's interested in a solution that doesn't work, and it's wasted reading that obfuscates the correct answer at the bottom, which works wonderfully.
                – Cerin
                Aug 3 at 16:47












              • @Cerin If you mean removing the "Error to avoid" I am going to keep it there. It shares common pitfall to avoid and it is very short. I am sure, someone would try optimizing the solution by providing all the things into variable (this happened to me), so I tried to shorten the path to success.
                – Jan Vlcinsky
                Aug 4 at 20:14


















              • Thanks. Just note: use "$@" instead of $* for pass-thru arguments, as the former behaves correctly when arguments contain whitespace.
                – Piotr Findeisen
                Mar 31 '16 at 7:39










              • @PiotrFindeisen Thanks for your note. However, I do not understand it completely - in zsh it helps me to keep strings with space in one piece, but in bash not. Can you tell me more or point to some explanation? I do not want to add some modification blindly.
                – Jan Vlcinsky
                Mar 31 '16 at 10:33










              • You should remove the first half of your answer. No one's interested in a solution that doesn't work, and it's wasted reading that obfuscates the correct answer at the bottom, which works wonderfully.
                – Cerin
                Aug 3 at 16:47












              • @Cerin If you mean removing the "Error to avoid" I am going to keep it there. It shares common pitfall to avoid and it is very short. I am sure, someone would try optimizing the solution by providing all the things into variable (this happened to me), so I tried to shorten the path to success.
                – Jan Vlcinsky
                Aug 4 at 20:14
















              Thanks. Just note: use "$@" instead of $* for pass-thru arguments, as the former behaves correctly when arguments contain whitespace.
              – Piotr Findeisen
              Mar 31 '16 at 7:39




              Thanks. Just note: use "$@" instead of $* for pass-thru arguments, as the former behaves correctly when arguments contain whitespace.
              – Piotr Findeisen
              Mar 31 '16 at 7:39












              @PiotrFindeisen Thanks for your note. However, I do not understand it completely - in zsh it helps me to keep strings with space in one piece, but in bash not. Can you tell me more or point to some explanation? I do not want to add some modification blindly.
              – Jan Vlcinsky
              Mar 31 '16 at 10:33




              @PiotrFindeisen Thanks for your note. However, I do not understand it completely - in zsh it helps me to keep strings with space in one piece, but in bash not. Can you tell me more or point to some explanation? I do not want to add some modification blindly.
              – Jan Vlcinsky
              Mar 31 '16 at 10:33












              You should remove the first half of your answer. No one's interested in a solution that doesn't work, and it's wasted reading that obfuscates the correct answer at the bottom, which works wonderfully.
              – Cerin
              Aug 3 at 16:47






              You should remove the first half of your answer. No one's interested in a solution that doesn't work, and it's wasted reading that obfuscates the correct answer at the bottom, which works wonderfully.
              – Cerin
              Aug 3 at 16:47














              @Cerin If you mean removing the "Error to avoid" I am going to keep it there. It shares common pitfall to avoid and it is very short. I am sure, someone would try optimizing the solution by providing all the things into variable (this happened to me), so I tried to shorten the path to success.
              – Jan Vlcinsky
              Aug 4 at 20:14




              @Cerin If you mean removing the "Error to avoid" I am going to keep it there. It shares common pitfall to avoid and it is very short. I am sure, someone would try optimizing the solution by providing all the things into variable (this happened to me), so I tried to shorten the path to success.
              – Jan Vlcinsky
              Aug 4 at 20:14










              up vote
              9
              down vote













              Use custom host config in ~/.ssh/config, like this:



              Host gitlab-as-thuc  
              HostName github.com
              User git
              IdentityFile ~/.ssh/id_rsa.thuc
              IdentitiesOnly yes


              then use your custom hostname like this:



              git remote add thuc git@gitlab-as-thuc:your-repo.git  





              share|improve this answer



















              • 1




                This is the answer I was looking for, as I have separate GitHub accounts for home and work. I just had to set Host work.github.com HostName github.com IdentityFile ~/.ssh/work, and then replace "github.com" by "work.github.com" whenever I clone a work repository. It still connects to "github.com", but using a non-default key pair.
                – Mikkel
                May 25 '16 at 17:06








              • 1




                The URL for details ("itblog.study.land/...") doesn't work any more :(
                – Carl Smotricz
                Sep 15 '17 at 8:10










              • @CarlSmotricz the original one was moved here: medium.com/@thucnc/…
                – thucnguyen
                Nov 27 at 7:13






              • 1




                FINALLY!!! This answer actually shows how you can utilize what you put in the ~/.ssh/config file. Every other answer misses how you can set the host when you add the origin, which automatically allows git to use the correct key file. THANK YOU!!
                – BrianVPS
                Dec 4 at 15:17















              up vote
              9
              down vote













              Use custom host config in ~/.ssh/config, like this:



              Host gitlab-as-thuc  
              HostName github.com
              User git
              IdentityFile ~/.ssh/id_rsa.thuc
              IdentitiesOnly yes


              then use your custom hostname like this:



              git remote add thuc git@gitlab-as-thuc:your-repo.git  





              share|improve this answer



















              • 1




                This is the answer I was looking for, as I have separate GitHub accounts for home and work. I just had to set Host work.github.com HostName github.com IdentityFile ~/.ssh/work, and then replace "github.com" by "work.github.com" whenever I clone a work repository. It still connects to "github.com", but using a non-default key pair.
                – Mikkel
                May 25 '16 at 17:06








              • 1




                The URL for details ("itblog.study.land/...") doesn't work any more :(
                – Carl Smotricz
                Sep 15 '17 at 8:10










              • @CarlSmotricz the original one was moved here: medium.com/@thucnc/…
                – thucnguyen
                Nov 27 at 7:13






              • 1




                FINALLY!!! This answer actually shows how you can utilize what you put in the ~/.ssh/config file. Every other answer misses how you can set the host when you add the origin, which automatically allows git to use the correct key file. THANK YOU!!
                – BrianVPS
                Dec 4 at 15:17













              up vote
              9
              down vote










              up vote
              9
              down vote









              Use custom host config in ~/.ssh/config, like this:



              Host gitlab-as-thuc  
              HostName github.com
              User git
              IdentityFile ~/.ssh/id_rsa.thuc
              IdentitiesOnly yes


              then use your custom hostname like this:



              git remote add thuc git@gitlab-as-thuc:your-repo.git  





              share|improve this answer














              Use custom host config in ~/.ssh/config, like this:



              Host gitlab-as-thuc  
              HostName github.com
              User git
              IdentityFile ~/.ssh/id_rsa.thuc
              IdentitiesOnly yes


              then use your custom hostname like this:



              git remote add thuc git@gitlab-as-thuc:your-repo.git  






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Apr 18 at 4:53

























              answered May 17 '16 at 15:03









              thucnguyen

              19913




              19913








              • 1




                This is the answer I was looking for, as I have separate GitHub accounts for home and work. I just had to set Host work.github.com HostName github.com IdentityFile ~/.ssh/work, and then replace "github.com" by "work.github.com" whenever I clone a work repository. It still connects to "github.com", but using a non-default key pair.
                – Mikkel
                May 25 '16 at 17:06








              • 1




                The URL for details ("itblog.study.land/...") doesn't work any more :(
                – Carl Smotricz
                Sep 15 '17 at 8:10










              • @CarlSmotricz the original one was moved here: medium.com/@thucnc/…
                – thucnguyen
                Nov 27 at 7:13






              • 1




                FINALLY!!! This answer actually shows how you can utilize what you put in the ~/.ssh/config file. Every other answer misses how you can set the host when you add the origin, which automatically allows git to use the correct key file. THANK YOU!!
                – BrianVPS
                Dec 4 at 15:17














              • 1




                This is the answer I was looking for, as I have separate GitHub accounts for home and work. I just had to set Host work.github.com HostName github.com IdentityFile ~/.ssh/work, and then replace "github.com" by "work.github.com" whenever I clone a work repository. It still connects to "github.com", but using a non-default key pair.
                – Mikkel
                May 25 '16 at 17:06








              • 1




                The URL for details ("itblog.study.land/...") doesn't work any more :(
                – Carl Smotricz
                Sep 15 '17 at 8:10










              • @CarlSmotricz the original one was moved here: medium.com/@thucnc/…
                – thucnguyen
                Nov 27 at 7:13






              • 1




                FINALLY!!! This answer actually shows how you can utilize what you put in the ~/.ssh/config file. Every other answer misses how you can set the host when you add the origin, which automatically allows git to use the correct key file. THANK YOU!!
                – BrianVPS
                Dec 4 at 15:17








              1




              1




              This is the answer I was looking for, as I have separate GitHub accounts for home and work. I just had to set Host work.github.com HostName github.com IdentityFile ~/.ssh/work, and then replace "github.com" by "work.github.com" whenever I clone a work repository. It still connects to "github.com", but using a non-default key pair.
              – Mikkel
              May 25 '16 at 17:06






              This is the answer I was looking for, as I have separate GitHub accounts for home and work. I just had to set Host work.github.com HostName github.com IdentityFile ~/.ssh/work, and then replace "github.com" by "work.github.com" whenever I clone a work repository. It still connects to "github.com", but using a non-default key pair.
              – Mikkel
              May 25 '16 at 17:06






              1




              1




              The URL for details ("itblog.study.land/...") doesn't work any more :(
              – Carl Smotricz
              Sep 15 '17 at 8:10




              The URL for details ("itblog.study.land/...") doesn't work any more :(
              – Carl Smotricz
              Sep 15 '17 at 8:10












              @CarlSmotricz the original one was moved here: medium.com/@thucnc/…
              – thucnguyen
              Nov 27 at 7:13




              @CarlSmotricz the original one was moved here: medium.com/@thucnc/…
              – thucnguyen
              Nov 27 at 7:13




              1




              1




              FINALLY!!! This answer actually shows how you can utilize what you put in the ~/.ssh/config file. Every other answer misses how you can set the host when you add the origin, which automatically allows git to use the correct key file. THANK YOU!!
              – BrianVPS
              Dec 4 at 15:17




              FINALLY!!! This answer actually shows how you can utilize what you put in the ~/.ssh/config file. Every other answer misses how you can set the host when you add the origin, which automatically allows git to use the correct key file. THANK YOU!!
              – BrianVPS
              Dec 4 at 15:17










              up vote
              5
              down vote













              You can just use ssh-ident instead of creating your own wrapper.



              You can read more at:
              https://github.com/ccontavalli/ssh-ident



              It loads ssh keys on demand when first needed, once, even with multiple login sessions, xterms or NFS shared homes.



              With a tiny config file, it can automatically load different keys and keep them separated in different agents (for agent forwarding) depending on what you need to do.






              share|improve this answer



























                up vote
                5
                down vote













                You can just use ssh-ident instead of creating your own wrapper.



                You can read more at:
                https://github.com/ccontavalli/ssh-ident



                It loads ssh keys on demand when first needed, once, even with multiple login sessions, xterms or NFS shared homes.



                With a tiny config file, it can automatically load different keys and keep them separated in different agents (for agent forwarding) depending on what you need to do.






                share|improve this answer

























                  up vote
                  5
                  down vote










                  up vote
                  5
                  down vote









                  You can just use ssh-ident instead of creating your own wrapper.



                  You can read more at:
                  https://github.com/ccontavalli/ssh-ident



                  It loads ssh keys on demand when first needed, once, even with multiple login sessions, xterms or NFS shared homes.



                  With a tiny config file, it can automatically load different keys and keep them separated in different agents (for agent forwarding) depending on what you need to do.






                  share|improve this answer














                  You can just use ssh-ident instead of creating your own wrapper.



                  You can read more at:
                  https://github.com/ccontavalli/ssh-ident



                  It loads ssh keys on demand when first needed, once, even with multiple login sessions, xterms or NFS shared homes.



                  With a tiny config file, it can automatically load different keys and keep them separated in different agents (for agent forwarding) depending on what you need to do.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jul 15 '14 at 18:44









                  Community

                  1




                  1










                  answered Mar 23 '13 at 1:35









                  rabexc

                  16112




                  16112






















                      up vote
                      4
                      down vote













                      I had a client that needed a separate github account. So I needed to use a separate key just for this one project.



                      My solution was to add this to my .zshrc / .bashrc:



                      alias infogit="GIT_SSH_COMMAND="ssh -i ~/.ssh/id_specialkey" git $@"


                      Whenever I want to use git for that project I replace "infogit" with git:



                      infogit commit -am "Some message" && infogit push


                      For me, it's easier to remember.






                      share|improve this answer

























                        up vote
                        4
                        down vote













                        I had a client that needed a separate github account. So I needed to use a separate key just for this one project.



                        My solution was to add this to my .zshrc / .bashrc:



                        alias infogit="GIT_SSH_COMMAND="ssh -i ~/.ssh/id_specialkey" git $@"


                        Whenever I want to use git for that project I replace "infogit" with git:



                        infogit commit -am "Some message" && infogit push


                        For me, it's easier to remember.






                        share|improve this answer























                          up vote
                          4
                          down vote










                          up vote
                          4
                          down vote









                          I had a client that needed a separate github account. So I needed to use a separate key just for this one project.



                          My solution was to add this to my .zshrc / .bashrc:



                          alias infogit="GIT_SSH_COMMAND="ssh -i ~/.ssh/id_specialkey" git $@"


                          Whenever I want to use git for that project I replace "infogit" with git:



                          infogit commit -am "Some message" && infogit push


                          For me, it's easier to remember.






                          share|improve this answer












                          I had a client that needed a separate github account. So I needed to use a separate key just for this one project.



                          My solution was to add this to my .zshrc / .bashrc:



                          alias infogit="GIT_SSH_COMMAND="ssh -i ~/.ssh/id_specialkey" git $@"


                          Whenever I want to use git for that project I replace "infogit" with git:



                          infogit commit -am "Some message" && infogit push


                          For me, it's easier to remember.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 26 at 19:26









                          Michael Cole

                          1634




                          1634






















                              up vote
                              2
                              down vote













                              My solution was this:



                              create a script:



                              #!/bin/bash
                              KEY=dafault_key_to_be_used
                              PORT=10022 #default port...
                              for i in $@;do
                              case $i in
                              --port=*)
                              PORT="${i:7}";;
                              --key=*)KEY="${i:6}";;
                              esac
                              done
                              export GIT_SSH_COMMAND="ssh -i $HOME/.ssh/${KEY} -p ${PORT}"
                              echo Command: $GIT_SSH_COMMAND


                              then when you have to change the var run:



                              . ./thescript.sh [--port=] [--key=]


                              Don't forget the extra dot!! this makes the script set the environments vars!! --key and --port are optional.






                              share|improve this answer

























                                up vote
                                2
                                down vote













                                My solution was this:



                                create a script:



                                #!/bin/bash
                                KEY=dafault_key_to_be_used
                                PORT=10022 #default port...
                                for i in $@;do
                                case $i in
                                --port=*)
                                PORT="${i:7}";;
                                --key=*)KEY="${i:6}";;
                                esac
                                done
                                export GIT_SSH_COMMAND="ssh -i $HOME/.ssh/${KEY} -p ${PORT}"
                                echo Command: $GIT_SSH_COMMAND


                                then when you have to change the var run:



                                . ./thescript.sh [--port=] [--key=]


                                Don't forget the extra dot!! this makes the script set the environments vars!! --key and --port are optional.






                                share|improve this answer























                                  up vote
                                  2
                                  down vote










                                  up vote
                                  2
                                  down vote









                                  My solution was this:



                                  create a script:



                                  #!/bin/bash
                                  KEY=dafault_key_to_be_used
                                  PORT=10022 #default port...
                                  for i in $@;do
                                  case $i in
                                  --port=*)
                                  PORT="${i:7}";;
                                  --key=*)KEY="${i:6}";;
                                  esac
                                  done
                                  export GIT_SSH_COMMAND="ssh -i $HOME/.ssh/${KEY} -p ${PORT}"
                                  echo Command: $GIT_SSH_COMMAND


                                  then when you have to change the var run:



                                  . ./thescript.sh [--port=] [--key=]


                                  Don't forget the extra dot!! this makes the script set the environments vars!! --key and --port are optional.






                                  share|improve this answer












                                  My solution was this:



                                  create a script:



                                  #!/bin/bash
                                  KEY=dafault_key_to_be_used
                                  PORT=10022 #default port...
                                  for i in $@;do
                                  case $i in
                                  --port=*)
                                  PORT="${i:7}";;
                                  --key=*)KEY="${i:6}";;
                                  esac
                                  done
                                  export GIT_SSH_COMMAND="ssh -i $HOME/.ssh/${KEY} -p ${PORT}"
                                  echo Command: $GIT_SSH_COMMAND


                                  then when you have to change the var run:



                                  . ./thescript.sh [--port=] [--key=]


                                  Don't forget the extra dot!! this makes the script set the environments vars!! --key and --port are optional.







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Dec 5 '15 at 12:22









                                  Salsicha

                                  211




                                  211






















                                      up vote
                                      2
                                      down vote













                                      So I set the GIT_SSH env variable to $HOME/bin/git-ssh.



                                      In order to support having my repo configuration dictate which ssh identity to use, my ~/bin/git-ssh file is this:



                                      #!/bin/sh
                                      ssh -i $(git config --get ssh.identity) -F /dev/null -p 22 $*


                                      Then I have a global git config setting:



                                      $ git config --global ssh.identity ~/.ssh/default_id_rsa


                                      And within any git repository I can just set a local ssh.identity git config value:



                                      $ git config --local ssh.identity ~/.ssh/any_other_id_rsa


                                      Voila!



                                      If you can have a different email address for each identity, it gets even simpler, because you can just name your keys after your email addresses and then have the git config's user.email drive the key selection in a ~/bin/git-ssh like this:



                                      #!/bin/sh
                                      ssh -i $HOME/.ssh/$(git config --get user.email) -F /dev/null -p 22 $*





                                      share|improve this answer



























                                        up vote
                                        2
                                        down vote













                                        So I set the GIT_SSH env variable to $HOME/bin/git-ssh.



                                        In order to support having my repo configuration dictate which ssh identity to use, my ~/bin/git-ssh file is this:



                                        #!/bin/sh
                                        ssh -i $(git config --get ssh.identity) -F /dev/null -p 22 $*


                                        Then I have a global git config setting:



                                        $ git config --global ssh.identity ~/.ssh/default_id_rsa


                                        And within any git repository I can just set a local ssh.identity git config value:



                                        $ git config --local ssh.identity ~/.ssh/any_other_id_rsa


                                        Voila!



                                        If you can have a different email address for each identity, it gets even simpler, because you can just name your keys after your email addresses and then have the git config's user.email drive the key selection in a ~/bin/git-ssh like this:



                                        #!/bin/sh
                                        ssh -i $HOME/.ssh/$(git config --get user.email) -F /dev/null -p 22 $*





                                        share|improve this answer

























                                          up vote
                                          2
                                          down vote










                                          up vote
                                          2
                                          down vote









                                          So I set the GIT_SSH env variable to $HOME/bin/git-ssh.



                                          In order to support having my repo configuration dictate which ssh identity to use, my ~/bin/git-ssh file is this:



                                          #!/bin/sh
                                          ssh -i $(git config --get ssh.identity) -F /dev/null -p 22 $*


                                          Then I have a global git config setting:



                                          $ git config --global ssh.identity ~/.ssh/default_id_rsa


                                          And within any git repository I can just set a local ssh.identity git config value:



                                          $ git config --local ssh.identity ~/.ssh/any_other_id_rsa


                                          Voila!



                                          If you can have a different email address for each identity, it gets even simpler, because you can just name your keys after your email addresses and then have the git config's user.email drive the key selection in a ~/bin/git-ssh like this:



                                          #!/bin/sh
                                          ssh -i $HOME/.ssh/$(git config --get user.email) -F /dev/null -p 22 $*





                                          share|improve this answer














                                          So I set the GIT_SSH env variable to $HOME/bin/git-ssh.



                                          In order to support having my repo configuration dictate which ssh identity to use, my ~/bin/git-ssh file is this:



                                          #!/bin/sh
                                          ssh -i $(git config --get ssh.identity) -F /dev/null -p 22 $*


                                          Then I have a global git config setting:



                                          $ git config --global ssh.identity ~/.ssh/default_id_rsa


                                          And within any git repository I can just set a local ssh.identity git config value:



                                          $ git config --local ssh.identity ~/.ssh/any_other_id_rsa


                                          Voila!



                                          If you can have a different email address for each identity, it gets even simpler, because you can just name your keys after your email addresses and then have the git config's user.email drive the key selection in a ~/bin/git-ssh like this:



                                          #!/bin/sh
                                          ssh -i $HOME/.ssh/$(git config --get user.email) -F /dev/null -p 22 $*






                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Dec 5 at 23:27

























                                          answered Dec 4 at 22:21









                                          Brendan Baldwin

                                          213




                                          213






















                                              up vote
                                              1
                                              down vote













                                              Generally, you want to use ~/.ssh/config for this. Simply pair server addresses with the keys you want to use for them as follows:



                                              Host github.com
                                              IdentityFile ~/.ssh/id_rsa.github
                                              Host heroku.com
                                              IdentityFile ~/.ssh/id_rsa.heroku
                                              Host *
                                              IdentityFile ~/.ssh/id_rsa


                                              Host * denotes any server, so I use it to set ~/.ssh/id_rsa as the default key to use.






                                              share|improve this answer

























                                                up vote
                                                1
                                                down vote













                                                Generally, you want to use ~/.ssh/config for this. Simply pair server addresses with the keys you want to use for them as follows:



                                                Host github.com
                                                IdentityFile ~/.ssh/id_rsa.github
                                                Host heroku.com
                                                IdentityFile ~/.ssh/id_rsa.heroku
                                                Host *
                                                IdentityFile ~/.ssh/id_rsa


                                                Host * denotes any server, so I use it to set ~/.ssh/id_rsa as the default key to use.






                                                share|improve this answer























                                                  up vote
                                                  1
                                                  down vote










                                                  up vote
                                                  1
                                                  down vote









                                                  Generally, you want to use ~/.ssh/config for this. Simply pair server addresses with the keys you want to use for them as follows:



                                                  Host github.com
                                                  IdentityFile ~/.ssh/id_rsa.github
                                                  Host heroku.com
                                                  IdentityFile ~/.ssh/id_rsa.heroku
                                                  Host *
                                                  IdentityFile ~/.ssh/id_rsa


                                                  Host * denotes any server, so I use it to set ~/.ssh/id_rsa as the default key to use.






                                                  share|improve this answer












                                                  Generally, you want to use ~/.ssh/config for this. Simply pair server addresses with the keys you want to use for them as follows:



                                                  Host github.com
                                                  IdentityFile ~/.ssh/id_rsa.github
                                                  Host heroku.com
                                                  IdentityFile ~/.ssh/id_rsa.heroku
                                                  Host *
                                                  IdentityFile ~/.ssh/id_rsa


                                                  Host * denotes any server, so I use it to set ~/.ssh/id_rsa as the default key to use.







                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Feb 11 '16 at 22:44









                                                  Zaz

                                                  1,32521230




                                                  1,32521230






















                                                      up vote
                                                      1
                                                      down vote













                                                      I build on @shellholic and this SO thread with a few teaks. I use GitHub as an example and assume that you have a private key in ~/.ssh/github (otherwise, see this SO thread) and that you added the public key to your GitHub profile (otherwise see GitHub's help).



                                                      If needed, create a new SSH config file at ~/.ssh/config and change permissions to 400



                                                      touch ~/.ssh/config
                                                      chmod 600 ~/.ssh/config


                                                      Add this to the ~/.ssh/config file:



                                                      Host github.com
                                                      IdentityFile ~/.ssh/github
                                                      IdentitiesOnly yes


                                                      If you already have a remote set up, you may want to delete it, otherwise you may still be prompted for username and password:



                                                      git remote rm origin


                                                      Then add a remote to the git repository, and notice the colon before the user name:



                                                      git remote add origin git@github.com:user_name/repo_name.git


                                                      And then git commands work normally, e.g.:



                                                      git push origin master
                                                      git pull origin


                                                      @HeyWatchThis on this SO thread suggested adding IdentitiesOnly yes to prevent the SSH default behavior of sending the identity file matching the default filename for each protocol. See that thread for more information and references.






                                                      share|improve this answer





















                                                      • This was my mistake: "If you already have a remote set up...". Thanks a lot!!!
                                                        – Allan Andrade
                                                        Oct 4 at 17:43















                                                      up vote
                                                      1
                                                      down vote













                                                      I build on @shellholic and this SO thread with a few teaks. I use GitHub as an example and assume that you have a private key in ~/.ssh/github (otherwise, see this SO thread) and that you added the public key to your GitHub profile (otherwise see GitHub's help).



                                                      If needed, create a new SSH config file at ~/.ssh/config and change permissions to 400



                                                      touch ~/.ssh/config
                                                      chmod 600 ~/.ssh/config


                                                      Add this to the ~/.ssh/config file:



                                                      Host github.com
                                                      IdentityFile ~/.ssh/github
                                                      IdentitiesOnly yes


                                                      If you already have a remote set up, you may want to delete it, otherwise you may still be prompted for username and password:



                                                      git remote rm origin


                                                      Then add a remote to the git repository, and notice the colon before the user name:



                                                      git remote add origin git@github.com:user_name/repo_name.git


                                                      And then git commands work normally, e.g.:



                                                      git push origin master
                                                      git pull origin


                                                      @HeyWatchThis on this SO thread suggested adding IdentitiesOnly yes to prevent the SSH default behavior of sending the identity file matching the default filename for each protocol. See that thread for more information and references.






                                                      share|improve this answer





















                                                      • This was my mistake: "If you already have a remote set up...". Thanks a lot!!!
                                                        – Allan Andrade
                                                        Oct 4 at 17:43













                                                      up vote
                                                      1
                                                      down vote










                                                      up vote
                                                      1
                                                      down vote









                                                      I build on @shellholic and this SO thread with a few teaks. I use GitHub as an example and assume that you have a private key in ~/.ssh/github (otherwise, see this SO thread) and that you added the public key to your GitHub profile (otherwise see GitHub's help).



                                                      If needed, create a new SSH config file at ~/.ssh/config and change permissions to 400



                                                      touch ~/.ssh/config
                                                      chmod 600 ~/.ssh/config


                                                      Add this to the ~/.ssh/config file:



                                                      Host github.com
                                                      IdentityFile ~/.ssh/github
                                                      IdentitiesOnly yes


                                                      If you already have a remote set up, you may want to delete it, otherwise you may still be prompted for username and password:



                                                      git remote rm origin


                                                      Then add a remote to the git repository, and notice the colon before the user name:



                                                      git remote add origin git@github.com:user_name/repo_name.git


                                                      And then git commands work normally, e.g.:



                                                      git push origin master
                                                      git pull origin


                                                      @HeyWatchThis on this SO thread suggested adding IdentitiesOnly yes to prevent the SSH default behavior of sending the identity file matching the default filename for each protocol. See that thread for more information and references.






                                                      share|improve this answer












                                                      I build on @shellholic and this SO thread with a few teaks. I use GitHub as an example and assume that you have a private key in ~/.ssh/github (otherwise, see this SO thread) and that you added the public key to your GitHub profile (otherwise see GitHub's help).



                                                      If needed, create a new SSH config file at ~/.ssh/config and change permissions to 400



                                                      touch ~/.ssh/config
                                                      chmod 600 ~/.ssh/config


                                                      Add this to the ~/.ssh/config file:



                                                      Host github.com
                                                      IdentityFile ~/.ssh/github
                                                      IdentitiesOnly yes


                                                      If you already have a remote set up, you may want to delete it, otherwise you may still be prompted for username and password:



                                                      git remote rm origin


                                                      Then add a remote to the git repository, and notice the colon before the user name:



                                                      git remote add origin git@github.com:user_name/repo_name.git


                                                      And then git commands work normally, e.g.:



                                                      git push origin master
                                                      git pull origin


                                                      @HeyWatchThis on this SO thread suggested adding IdentitiesOnly yes to prevent the SSH default behavior of sending the identity file matching the default filename for each protocol. See that thread for more information and references.







                                                      share|improve this answer












                                                      share|improve this answer



                                                      share|improve this answer










                                                      answered May 3 at 10:17









                                                      mmorin

                                                      2118




                                                      2118












                                                      • This was my mistake: "If you already have a remote set up...". Thanks a lot!!!
                                                        – Allan Andrade
                                                        Oct 4 at 17:43


















                                                      • This was my mistake: "If you already have a remote set up...". Thanks a lot!!!
                                                        – Allan Andrade
                                                        Oct 4 at 17:43
















                                                      This was my mistake: "If you already have a remote set up...". Thanks a lot!!!
                                                      – Allan Andrade
                                                      Oct 4 at 17:43




                                                      This was my mistake: "If you already have a remote set up...". Thanks a lot!!!
                                                      – Allan Andrade
                                                      Oct 4 at 17:43










                                                      up vote
                                                      0
                                                      down vote













                                                      I'm using git version 2.16 and I don't need a single piece of script not even a config or modified commands.




                                                      • Just copied my private key to .ssh/id_rsa

                                                      • set permissions to 600


                                                      And git reads to key automatically. I doesn't ask anything and it doesn't throw an error. Just works fine.






                                                      share|improve this answer





















                                                      • Did you notice that the question is about “a system with multiple private keys in the ~/.ssh directory”?
                                                        – Scott
                                                        Jun 6 at 5:16















                                                      up vote
                                                      0
                                                      down vote













                                                      I'm using git version 2.16 and I don't need a single piece of script not even a config or modified commands.




                                                      • Just copied my private key to .ssh/id_rsa

                                                      • set permissions to 600


                                                      And git reads to key automatically. I doesn't ask anything and it doesn't throw an error. Just works fine.






                                                      share|improve this answer





















                                                      • Did you notice that the question is about “a system with multiple private keys in the ~/.ssh directory”?
                                                        – Scott
                                                        Jun 6 at 5:16













                                                      up vote
                                                      0
                                                      down vote










                                                      up vote
                                                      0
                                                      down vote









                                                      I'm using git version 2.16 and I don't need a single piece of script not even a config or modified commands.




                                                      • Just copied my private key to .ssh/id_rsa

                                                      • set permissions to 600


                                                      And git reads to key automatically. I doesn't ask anything and it doesn't throw an error. Just works fine.






                                                      share|improve this answer












                                                      I'm using git version 2.16 and I don't need a single piece of script not even a config or modified commands.




                                                      • Just copied my private key to .ssh/id_rsa

                                                      • set permissions to 600


                                                      And git reads to key automatically. I doesn't ask anything and it doesn't throw an error. Just works fine.







                                                      share|improve this answer












                                                      share|improve this answer



                                                      share|improve this answer










                                                      answered Jun 6 at 4:37









                                                      AKPrajapati

                                                      112




                                                      112












                                                      • Did you notice that the question is about “a system with multiple private keys in the ~/.ssh directory”?
                                                        – Scott
                                                        Jun 6 at 5:16


















                                                      • Did you notice that the question is about “a system with multiple private keys in the ~/.ssh directory”?
                                                        – Scott
                                                        Jun 6 at 5:16
















                                                      Did you notice that the question is about “a system with multiple private keys in the ~/.ssh directory”?
                                                      – Scott
                                                      Jun 6 at 5:16




                                                      Did you notice that the question is about “a system with multiple private keys in the ~/.ssh directory”?
                                                      – Scott
                                                      Jun 6 at 5:16










                                                      up vote
                                                      0
                                                      down vote













                                                      Just use ssh-agent and ssh-add commands.



                                                      # create a agent
                                                      ssh-agent

                                                      # add your default key
                                                      ssh-add ~/.ssh/id_rsa

                                                      # add your second key
                                                      ssh-add ~/.ssh/<your key name>


                                                      After execute above commands, you can use both key as same time.
                                                      Just type



                                                      git clone git@github.com:<yourname>/<your-repo>.git


                                                      to connect your repository.



                                                      You need to execute above command after you reboot your machine.



                                                      English is not my native language; please excuse typing errors.






                                                      share|improve this answer



























                                                        up vote
                                                        0
                                                        down vote













                                                        Just use ssh-agent and ssh-add commands.



                                                        # create a agent
                                                        ssh-agent

                                                        # add your default key
                                                        ssh-add ~/.ssh/id_rsa

                                                        # add your second key
                                                        ssh-add ~/.ssh/<your key name>


                                                        After execute above commands, you can use both key as same time.
                                                        Just type



                                                        git clone git@github.com:<yourname>/<your-repo>.git


                                                        to connect your repository.



                                                        You need to execute above command after you reboot your machine.



                                                        English is not my native language; please excuse typing errors.






                                                        share|improve this answer

























                                                          up vote
                                                          0
                                                          down vote










                                                          up vote
                                                          0
                                                          down vote









                                                          Just use ssh-agent and ssh-add commands.



                                                          # create a agent
                                                          ssh-agent

                                                          # add your default key
                                                          ssh-add ~/.ssh/id_rsa

                                                          # add your second key
                                                          ssh-add ~/.ssh/<your key name>


                                                          After execute above commands, you can use both key as same time.
                                                          Just type



                                                          git clone git@github.com:<yourname>/<your-repo>.git


                                                          to connect your repository.



                                                          You need to execute above command after you reboot your machine.



                                                          English is not my native language; please excuse typing errors.






                                                          share|improve this answer














                                                          Just use ssh-agent and ssh-add commands.



                                                          # create a agent
                                                          ssh-agent

                                                          # add your default key
                                                          ssh-add ~/.ssh/id_rsa

                                                          # add your second key
                                                          ssh-add ~/.ssh/<your key name>


                                                          After execute above commands, you can use both key as same time.
                                                          Just type



                                                          git clone git@github.com:<yourname>/<your-repo>.git


                                                          to connect your repository.



                                                          You need to execute above command after you reboot your machine.



                                                          English is not my native language; please excuse typing errors.







                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Jul 5 at 9:58

























                                                          answered Jul 5 at 9:53









                                                          Jinmiao Luo

                                                          12




                                                          12






























                                                              draft saved

                                                              draft discarded




















































                                                              Thanks for contributing an answer to Super User!


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid



                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                              To learn more, see our tips on writing great answers.





                                                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                              Please pay close attention to the following guidance:


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid



                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                              To learn more, see our tips on writing great answers.




                                                              draft saved


                                                              draft discarded














                                                              StackExchange.ready(
                                                              function () {
                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f232373%2fhow-to-tell-git-which-private-key-to-use%23new-answer', 'question_page');
                                                              }
                                                              );

                                                              Post as a guest















                                                              Required, but never shown





















































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown

































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown







                                                              Popular posts from this blog

                                                              "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                                                              Alcedinidae

                                                              RAC Tourist Trophy