319

I'm having some trouble getting two different SSH keys/GitHub accounts to play well together. I have the following setup:

Repos accessible from one account using git@github.com:accountname

Repos accessible from another account using git@github.com:anotheraccount

Each account has its own SSH key. Both SSH keys have been added and I have created a config file. I don't believe the config file is correct though. I'm not quite sure how to specify that repos accessed using git@github.com:accountname should use id_rsa and git@github.com:anotheraccount should use id_rsa_anotheraccount.

Jeff Ames
  • 1,424
  • 10
  • 18
radesix
  • 5,834
  • 5
  • 24
  • 39
  • 1
    I found this link helpful https://medium.freecodecamp.org/manage-multiple-github-accounts-the-ssh-way-2dadc30ccaca – jgreen Apr 18 '19 at 17:57
  • I have 3 separate SSH identities in ~/.ssh/config. The one for school server has a passcode; the 2 for separate work/personal GitHub accts do not. Running `git pull` kept failing & asking for the school passcode, despite separate Identity files, "IdentitiesOnly=yes," separate domains & Hostnames, all present in `ssh-add -l` ... The uni key was 'first' regardless of that setup. Had to move its section below the others in .ssh/config, and now `git pull` from both GitHub accts succeeds w/o asking for uni ssh password. – mc01 May 28 '19 at 18:00
  • 1
    That is answered in detail here https://superuser.com/questions/232373/how-to-tell-git-which-private-key-to-use – Julius Š. Jul 22 '20 at 16:39
  • Check the [answer below](https://stackoverflow.com/a/50746763/1814970) with the `sshCommand` git config option. – marcelocra Aug 24 '22 at 17:31

14 Answers14

386

Andy Lester's response is accurate but I found an important extra step I needed to make to get this to work. In trying to get two profiles set up, one for personal and one for work, my ~/.ssh/config was roughly as follows:

Host me.github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/me_rsa

Host work.github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/work_rsa

My work profile didn't take until I did a ssh-add ~/.ssh/work_rsa. After that connections to github used the correct profile. Previously they defaulted to the first public key.

For Could not open a connection to your authentication agent when using ssh-add,
check: https://stackoverflow.com/a/17695338/1760313

Community
  • 1
  • 1
Jim Wrubel
  • 4,031
  • 1
  • 17
  • 12
  • By using ssh-add, I could see that I did not have the file permissions for the key set correctly. Once I fixed that everything worked. So thanks! – phatmann Jan 13 '12 at 15:55
  • 7
    See also http://doblock.com/articles/using-public-keys-with-multiple-github-accounts. The key new piece of info there is that you may need to add the username ("work", in this example) to the hostname in the remote URL, i.e., git@work.github.com:work/my_repo.git (as opposed to "git@github.com...") – BobS Mar 24 '12 at 19:33
  • 1
    This works: http://superuser.com/questions/232373/tell-git-which-private-key-to-use – Casey Mar 28 '12 at 21:16
  • 17
    To fix the problem that "they defaulted to the first public key", add `IdentitiesOnly yes` to the `Host *` section of your `~/.ssh/config` file. This tells ssh to actually use the IdentityFiles you specify, rather than spamming the server with all of them. – Mechanical snail May 09 '12 at 07:18
  • What does your private key look like? – James Raitsev Jun 19 '12 at 02:32
  • Just use my [`github-keygen`](https://github.com/dolmen/github-keygen) tool: `github-keygen me work` (*Yes, that's all!*). – dolmen Sep 20 '13 at 14:49
  • Note if you have a 'Host *' block with an 'IdentityFile' statement, to force a particular key, you need to negate the target hostname for that Host block - e.g. 'Host * !work.github.com' - that, in addition to IdentitiesOnly as @Mechanicalsnail suggests will force a particular key. – Von Sep 23 '13 at 02:38
  • Don't forget to run `chmod 600 ~/.ssh/config` if you has just created your config file. I was having trouble here. – Tulio Jan 16 '15 at 17:23
  • Hi everybody, do you know how I can have git to use differente emails for different accounts? e.g. i would like to push to me.github.com using me@email.com and to work.github.com using work@email.com – lucacerone Feb 27 '15 at 19:41
  • @lucacerone, you just need to change the user/email in the project scope. Change to the directory and type `git config user.name 'John Smith'` and then `git config user.email john@domain.com`. This will override your global config which can be seen by `git config --global user.name`. –  Mar 07 '15 at 01:36
  • what is the "Host" and "Host" name should be set if I am not using github but gitlab set up at company? – JaskeyLam Oct 20 '15 at 04:28
  • When i run ~/.ssh/config I get permission denied. – Saraschandraa Feb 22 '16 at 07:44
  • @Saraschandraa It shouldn't be run. It's a config (text) file you create. – JHH Apr 13 '16 at 15:51
  • On a related note, is it possible to add a comment in the .ssh/config file without messing it up? Just curious. I assume you can add some with `#`. – Barry Nov 10 '16 at 20:42
  • but what if there isn't a separate work doman like `work.github.com` ? – Paulo Dec 14 '17 at 12:57
  • I setup 3 hosts and this worked like a charm. I'm using Mac OSx High Sierra 10.13. – Val Mar 29 '18 at 03:19
  • This can be improved with `insteadOf ` : [Use different ssh keys for different github repos](https://public-inbox.org/git/966f577f-c4ca-46a4-d55d-817e84780324@gmail.com/) – basin Jul 19 '18 at 20:33
  • @Paulo, as I understand this, `Host` is used to tell which configurations to use. It is the name you use on the command line. But `Hostname` will tell `ssh` which machine to _actually_ connect to. That is why they point/use the same `Hostname` in both `Host` Stanzas. So, `ssh me.github,com` will actually connect to `github.com`, but use configurations from `me.github,com`. – Anders Sep 06 '19 at 13:58
  • I find it very frustrating that all the answers to this and related questions omit the last part: the git clone command to run to checkout the project using the git CLI and the ~/.ssh/config file! :( – rjurney Sep 24 '20 at 15:56
212

I recently had to do this and had to sift through all these answers and their comments to eventually piece the information together, so I'll put it all here, in one post, for your convenience:


Step 1: ssh keys
Create any keypairs you'll need. In this example I've named me default/original 'id_rsa' (which is the default) and my new one 'id_rsa-work':

ssh-keygen -t rsa -C "stefano@work.com"


Step 2: ssh config
Set up multiple ssh profiles by creating/modifying ~/.ssh/config. Note the slightly differing 'Host' values:

# Default GitHub
Host github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa

# Work GitHub
Host work.github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_work


Step 3: ssh-add
You may or may not have to do this. To check, list identity fingerprints by running:

$ ssh-add -l
2048 1f:1a:b8:69:cd:e3:ee:68:e1:c4:da:d8:96:7c:d0:6f stefano (RSA)
2048 6d:65:b9:3b:ff:9c:5a:54:1c:2f:6a:f7:44:03:84:3f stefano@work.com (RSA)

If your entries aren't there then run:

ssh-add ~/.ssh/id_rsa_work


Step 4: test
To test you've done this all correctly, I suggest the following quick check:

$ ssh -T git@github.com
Hi stefano! You've successfully authenticated, but GitHub does not provide shell access.

$ ssh -T git@work.github.com
Hi stefano! You've successfully authenticated, but GitHub does not provide shell access.

Note that you'll have to change the hostname (github / work.github) depending on what key/identity you'd like to use. But now you should be good to go! :)

stefano
  • 3,753
  • 1
  • 22
  • 15
  • 2
    This is a great response. I had to use ssh-add to add both the ssh keys to utilize the config file.. Thanks :) – gaurav.singharoy Apr 23 '14 at 19:05
  • The only thing I like to add is when you run ssh-keygen -t rsa, it will give you a default file name, that is where you enter your custom file name. – Daniel Viglione Sep 26 '16 at 16:29
  • One of best answers. Also this video helped me. https://www.youtube.com/watch?v=fnSRBRiQIU8&feature=youtu.be – TestingWithArif Mar 04 '18 at 11:58
  • Good post, would be nice if this post included setting your git config 'email': https://help.github.com/articles/setting-your-commit-email-address-in-git/ – Dave Engineer Dec 07 '18 at 16:39
  • If anyone else is getting "error connecting to agent" when doing "ssh-agent", check this out https://stackoverflow.com/questions/52113738/starting-ssh-agent-on-windows-10-fails-unable-to-start-ssh-agent-service-erro – uniquegino Dec 26 '20 at 00:35
55

Let's say alice is a github.com user, with 2 or more private repositories repoN. For this example we'll work with just two repositories named repo1 and repo2

https://github.com/alice/repo1

https://github.com/alice/repo2

You need to be to pull from these repositories without entering a passwords probably on a server, or on multiple servers. You want to perform git pull origin master for example, and you want this to happen without asking for a password.

You don't like dealing with ssh-agent, you have discovered (or you're discovering now) about ~/.ssh/config a file that let's your ssh client know what private key to use depending on Hostname and username, with a simple configuration entry that looks like this:

Host github.com
  HostName github.com
  User git
  IdentityFile /home/alice/.ssh/alice_github.id_rsa
  IdentitiesOnly yes

So you went ahead and created your (alice_github.id_rsa, alice_github.id_rsa.pub) keypair, you then also went to your repository's .git/config file and you modified the url of your remote origin to be something like this:

[remote "origin"]
        url = "ssh://git@github.com/alice/repo1.git"

And finally you went to the repository Settings > Deploy keys section and added the contents of alice_github.id_rsa.pub

At this point you could do your git pull origin master without entering a password without issue.

but what about the second repository?

So your instinct will be to grab that key and add it to repo2's Deploy keys, but github.com will error out and tell you that the key is already being used.

Now you go and generate another key (using ssh-keygen -t rsa -C "alice@alice.com" without passwords of course), and so that this doesn't become a mess, you will now name your keys like this:

  • repo1 keypair: (repo1.alice_github.id_rsa, repo1.alice_github.id_rsa.pub)
  • repo2 keypair: (repo2.alice_github.id_rsa, repo2.alice_github.id_rsa.pub)

You will now put the new public key on repo2's Deploy keys configuration at github.com, but now you have an ssh problem to deal with.

How can ssh tell which key to use if the repositories are hosted on the same github.com domain?

Your .ssh/config file points to github.com and it doesn't know which key to use when it's time to do the pull.

So I found a trick with github.com. You can tell your ssh client that each repository lives in a different github.com subdomain, in these cases, they will be repo1.github.com and repo2.github.com

So first thing is editing the .git/config files on your repo clones, so they look like this instead:

For repo1

[remote "origin"]
        url = "ssh://git@repo1.github.com/alice/repo1.git"

For repo2

[remote "origin"]
        url = "ssh://git@repo2.github.com/alice/repo2.git"

And then, on your .ssh/config file, now you will be able to enter a configuration for each subdomain :)

Host repo1.github.com
  HostName github.com
  User git
  IdentityFile /home/alice/.ssh/repo1.alice_github.id_rsa
  IdentitiesOnly yes

Host repo2.github.com
  HostName github.com
  User git
  IdentityFile /home/alice/.ssh/repo2.alice_github.id_rsa
  IdentitiesOnly yes

Now you are able to git pull origin master without entering any passwords from both repositories.

If you have multiple machines, you could copy the keys to each of the machines and reuse them, but I'd advise doing the leg work to generate 1 key per machine and repo. You will have a lot more keys to handle, but you will be less vulnerable if one gets compromised.

AliciaBytes
  • 7,300
  • 6
  • 36
  • 47
Gubatron
  • 6,222
  • 5
  • 35
  • 37
43

I have 2 accounts on github, and here is what I did (on linux) to make it work.

Keys

  • Create 2 pair of rsa keys, via ssh-keygen, name them properly, so that make life easier.
  • Add private keys to local agent via ssh-add path_to_private_key
  • For each github account, upload a (distinct) public key.

Configuration

~/.ssh/config

Host github-kc
    Hostname        github.com
    User git
    IdentityFile    ~/.ssh/github_rsa_kc.pub
    # LogLevel DEBUG3

Host github-abc
    Hostname        github.com
    User git
    IdentityFile    ~/.ssh/github_rsa_abc.pub
    # LogLevel DEBUG3

Set remote url for repo:

  • For repo in Host github-kc:

    git remote set-url origin git@github-kc:kuchaguangjie/pygtrans.git
    
  • For repo in Host github-abc:

    git remote set-url origin git@github-abc:abcdefg/yyy.git
    

Explaination

Options in ~/.ssh/config:

  • Host github-<identify_specific_user>
    Host could be any value that could identify a host plus an account, it don't need to be a real host, e.g github-kc identify one of my account on github for my local laptop,

    When set remote url for a git repo, this is the value to put after git@, that's how a repo maps to a Host, e.g git remote set-url origin git@github-kc:kuchaguangjie/pygtrans.git


  • [Following are sub options of Host]
  • Hostname
    specify the actual hostname, just use github.com for github,
  • User git
    the user is always git for github,
  • IdentityFile
    specify key to use, just put the path the a public key,
  • LogLevel
    specify log level to debug, if any issue, DEBUG3 gives the most detailed info.

Eric
  • 22,183
  • 20
  • 145
  • 196
  • lovely -- did not need `ssh-add path_to_private_key` -- probably because the agent isn't required in this case. The config file is explicitly defining the path to the keys. – Mark Chackerian May 26 '16 at 22:05
  • 4
    @MarkChackerian I think you don't need `ssh-add` because your keys aren't password protected or (if you're on a Mac) the OSX keychain is handling it for you. `ssh-add` prevents you from needing to enter the passphrase every time you access your keys. – Ashhar Hasan Oct 10 '16 at 22:53
  • Great, to the point and what I was looking for. Thanks – Dhaval Dec 26 '20 at 16:45
  • Excellent explanation. The key here is to use "git remote set-url ..." to tell git which ssh key to use by referencing the right host! – EricX Jul 25 '23 at 16:18
19

Use the IdentityFile parameter in your ~/.ssh/config:

Host github.com
    HostName github.com
    IdentityFile ~/.ssh/github.rsa
    User petdance
Yuval Adam
  • 161,610
  • 92
  • 305
  • 395
Andy Lester
  • 91,102
  • 13
  • 100
  • 152
  • Thanks but this isn't quite accurate. I found the answer and shared below. – radesix Jul 12 '10 at 04:36
  • I'm pretty sure my approach will work in your case. You can identify different users and different identity files. Just need to give each a different Host parameter on the config stanza. – Andy Lester Jul 12 '10 at 04:48
  • 1
    Andy, according to the link I found below I needed to drop the .com from the host. Once I did that it worked fine. – radesix Jul 13 '10 at 14:30
15

A possibly simpler alternative to editing the ssh config file (as suggested in all other answers), is to configure an individual repository to use a different (e.g. non-default) ssh key.

Inside the repository for which you want to use a different key, run:

git config core.sshCommand 'ssh -i ~/.ssh/id_rsa_anotheraccount'

If your key is passhprase-protected and you don't want to type your password every time, you have to add it to the ssh-agent. Here's how to do it for ubuntu and here for macOS.

It should also be possible to scale this approach to multiple repositories using global git config and conditional includes (see example).

Jakub Kukul
  • 12,032
  • 3
  • 54
  • 53
  • 1
    You can even configure this using `includeIf` in your global `.gitconfig`. – marcelocra Aug 24 '22 at 17:29
  • This answer was the most useful to me. I'd hate to have to change the URL manually every time I want to clone something, but this is easy to add to the script I'm already using to set my email address and other identity details per work directory before starting to work. – tripleee Aug 23 '23 at 09:02
9

I spent a lot of time to understand all the steps. So lets describe step by step:

  1. Create new identity file using ssh-keygen -t rsa. Give it an alternative like proj1.id_rsa and hit with no doubt because you don't need a passphrase.
  2. Add new section in .ssh/config:

    Host proj1.github.com
        HostName github.com
        PreferredAuthentications publickey
        IdentityFile ~/.ssh/proj1.id_rsa
    

Take into account the first section and note that proj1.github.com we will back to the section later.

  1. Add the identity to ssh agent ssh-add ~/.ssh/proj1.id_rsa
  2. That what I messed first time - now when you want to clone a proj1 repo you do it using proj1.github.com (exactly the host from the config file). git clone git@proj1.github.com.

A good tutorial.

Don't mess up with hosts

I159
  • 29,741
  • 31
  • 97
  • 132
  • Thanks for the link to the turorial! You have a typo: the key names `id_rsa_proj1` and `proj1_id_rsa` should actually be same. You could also add the part about `.git/config` settings from the tutorial to your answer. – cezar Feb 02 '18 at 12:46
  • You still have a typo: `proj1.id_rsa` vs. `proj1_id_rsa` – cezar Feb 02 '18 at 14:50
5

In my case none of the solutions above solved my issue, but ssh-agent does. Basically, I did the following:

  1. Generate key pair using ssh-keygen shown below. It will generate a key pair (in this example .\keyfile and .\keyfile.pub)

    ssh-keygen -t rsa -b 4096 -C "yourname@yourdomain" -f keyfile

  2. Upload keyfile.pub to the git provider

  3. Start ssh-agent on your machine (you can check with ps -ef | grep ssh-agent to see if it is running already)
  4. Run ssh-add .\keyfile to add credentials
  5. Now you can run git clone git@provider:username/project.git
berniey
  • 2,772
  • 1
  • 18
  • 8
3

As a complement of @stefano 's answer, It is better to use command with -f when generate a new SSH key for another account,

ssh-keygen -t rsa -f ~/.ssh/id_rsa_work -C "your@mail.com"

Since id_rsa_work file doesn't exist in path ~/.ssh/, and I create this file manually, and it doesn't work :(

Weiyi
  • 1,843
  • 2
  • 22
  • 34
3

Simplest way to use multiple Git accounts and clone without any changes would be to add your username to the ssh config.

  1. Open ~/.ssh/config. Create if one doesn't exist
  2. Add your host entry as following
Host github.com:<YOUR_GITHUB_USERNAME>
  AddKeysToAgent yes
  IdentityFile ~/.ssh/<YOUR_SSH_KEY_FILENAME>

Replace <YOUR_GITHUB_USERNAME> with your desired github username (personal or work) Replace <YOUR_SSH_KEY_FILENAME> with your keyfile name in .ssh folder (ex: id_ed25519). Add a host record for each of the github account you want to maintain.

Now git clone would be simple as git clone github.com:<YOUR_GITHUB_USERNAME>/your-repo.git. No custom gihub domains to remember when cloning ;-)

Made a gist with further information https://gist.github.com/udantha/fed5439630eaf4651272f4fba6e1c6a3

Udantha
  • 300
  • 3
  • 6
  • This is actually on of the best answers. With the `:` part being really important. The reason being is that let's say you want to reference a private git repo as a package in your package.json file, if you end up having to use something like: `"package" : "git+ssh://git@new-host:/.git"` Which means everyone has to update their .ssh config file to match yours. But if you include the `:` then you can be assured everyone can access it directly whether or not the have multiple ssh keys or not. – Jim Heising Jun 08 '23 at 20:03
  • But I can have different username / organisation where I want to push directly. In that case we have add multiple `host:username` combination. Directory based solution works well instead of configuring ssh config file update git config file `core.sshcommand = "ssh -i ~/.ssh/"` – Snigdhajyoti Aug 08 '23 at 21:54
2

I used,

Host github.com
   HostName github.com
   IdentityFile ~/.ssh/github_rsa
   User abc@gmail.com

It wokred fine.

Use the above setting in your .ssh/config file for different rsa keys for different usernames.

Jyoti Prakash
  • 3,921
  • 3
  • 21
  • 24
2

I posted the technique I use to deal with these here

David H
  • 40,852
  • 12
  • 92
  • 138
1

This is the only config that worked for me to be able to use two GitHub accounts with different SSH keys.

Replace id_ed25519 (representing my work SSH key) and id_ed25519-personal (representing my personal SSH key) with your SSH keys' filenames.

Host github.com
IdentitiesOnly yes
IdentityFile ~/.ssh/id_ed25519
IdentityFile ~/.ssh/id_ed25519-personal
Liran H
  • 9,143
  • 7
  • 39
  • 52
0

I find solution of this problem and try to explain it. We should make change in both file ~/.ssh/config and in ~/.gitconfig

Let's show.

1. Create keys

You will need one key for each different account you will use on either GitHub or BitBucket.

Whichever site you have more identities with determines how many keys you will need.

A single key can act both as a GitHub and BitBucket key but cannot be associated with more than one BitBucket or GitHub account.

If you already have created a key in ~/.ssh/id_rsa (the default location), you may use that in place of the ~/.ssh/msmith key in my examples or you can leave that key and add additional keys for the other identities.

Create the keys and ssh-add them (make sure to enter a secure password and do not just leave it blank)

$ ssh-keygen -t rsa -b 4096 -f ~/.ssh/key1_rsa -C "msmith@example.com" 

Generating public/private rsa key pair. Enter passphrase (empty for no passphrase): ************ Enter same passphrase again: Your identification has been saved in /Users/me/.ssh/key1_rsa. Your public key has been saved in /Users/me/.ssh/key1_rsa.pub. The key fingerprint is: ...

$  ssh-add ~/.ssh/key1_rsa
$  ssh-keygen -t rsa -b 4096 -f ~/.ssh/key2_rsa -C "jblige@example.com" 

Generating public/private rsa key pair. Enter passphrase (empty for no passphrase): ************ Enter same passphrase again: Your identification has been saved in /Users/me/.ssh/key2_rsa. Your public key has been saved in /Users/me/.ssh/key2_rsa.pub. The key fingerprint is: ...

$ ssh-add ~/.ssh/key2_rsa

2. Setup ~/.ssh/config

Create a file in ~/.ssh/config (if it does not already exist). You must make sure it is readable only by the owner and the group and public bits are set off.

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

We now need to add SSH configuration that specifies the github and bitbucket hostnames but with a suffix appended to qualify which key to use. We set the HostName to the correct github.com or bitbucket.org address.

Note: Linux users should either omit UseKeychain yes or add IgnoreUnknown UseKeychain (thanks soulofmischief)

~/.ssh/config
...

Host github.com-msmith
  HostName github.com
  UseKeychain yes
  AddKeysToAgent yes
  User git
  IdentityFile ~/.ssh/msmith_rsa
  IdentitiesOnly yes

Host bitbucket.org-msmith
  HostName bitbucket.org
  UseKeychain yes
  AddKeysToAgent yes
  User git
  IdentityFile ~/.ssh/msmith_rsa
  IdentitiesOnly yes

Host github.com-jblige
  HostName github.com
  UseKeychain yes
  AddKeysToAgent yes
  User git
  IdentityFile ~/.ssh/jblige_rsa
  IdentitiesOnly yes

Host bitbucket.org-jblige
  HostName bitbucket.org
  UseKeychain yes
  AddKeysToAgent yes
  User git
  IdentityFile ~/.ssh/jblige_rsa
  IdentitiesOnly yes

...

3. Add public keys to GitHub and BitBucket

Log into GitHub for each user and add the keys from ~/.ssh/xxxxx.pub to the respective users authorized SSH keys.

For more information on this see: https://confluence.atlassian.com/bitbucket/set-up-an-ssh-key-728138079.html

or

https://help.github.com/en/articles/adding-a-new-ssh-key-to-your-github-account

4. Create key specific .gitconfig

You will need a single directory where all code that corresponds to a given key will be checked out to.

I prefer to keep all those directories in one directory in my home ~/src and I name them according to the account name associated with the key

mkdir -p ~/src/msmith
mkdir -p ~/src/jblige

In each directory put a .gitconfig file.

~/src/msmith/.gitconfig
...
[user]
  email = msmith@example.com
    
[url "git@bitbucket.org-msmith"]
  insteadOf = git@bitbucket.org
  
[url "git@github.com-msmith"]
  insteadOf = git@github.com
~/src/jblige/.gitconfig
...
[user]
  email = jblige@example.com
  signingkey = ABCD1234
  
[url "git@bitbucket.org-jblige"]
  insteadOf = git@bitbucket.org
  
[url "git@github.com-jblige"]
  insteadOf = git@github.com
  
[commit]
  gpgsign = true

This way, I use the correct email address for both keys and have even set up automatic commit signing for jblige. I also rewrite all the hostnames for the original SSH connections to the correctly suffixed hostnames I created in the SSH config file.

For more information about GPG signing see:

https://help.github.com/en/articles/signing-commits

or

https://confluence.atlassian.com/bitbucketserver/using-gpg-keys-913477014.html

5. Setup Git config includeif

To activate the .gitconfig files in ~/src/*, edit the .gitconfig file in your home directory and add an includeif statement for each of the .gitconfig files referencing the directory they are in

~/.gitconfig
...

[includeif "gitdir:~/src/msmith/"]
    path = ~/src/msmith/.gitconfig
    
[includeif "gitdir:~/src/jblige/"]
    path = ~/src/jblige/.gitconfig
    

Do not forget the trailing slash in the [includeif "gitdir:... statement.

6. Cloning the repositories

You then clone the code using the SSH clone address (i.e. git@bitbucket.org... or git@github.com..., not https://bitbucket.org... nor https://github.com...) into the directory that corresponds to the key you want to use for that clone.

$  cd ~/src/msmith
$  git clone git@github.com:someuser/somerepo.git
...

Because of the rewriting, git will actually attempt to clone using the suffixed address corresponding to the configuration in the SSH config file but because of the SSH configuration it will use the original hostname when actually connecting to the host ensuring you use the right key.

All commits/pulls/pushes to/from those repositories will use the corresponding config/key/account.

mrkiril
  • 821
  • 12
  • 11