Skip to content

Instantly share code, notes, and snippets.

@JoaquimLey
Last active April 30, 2023 22:17
Star You must be signed in to star a gist
Save JoaquimLey/e6049a12c8fd2923611802384cd2fb4a to your computer and use it in GitHub Desktop.
How to Work with GitHub and Multiple Accounts

Step 1 - Create a New SSH Key

We need to generate a unique SSH key for our second GitHub account.

ssh-keygen -t rsa -C "your-email-address"

Be careful that you don't over-write your existing key for your personal account. Instead, when prompted, save the file as id_rsa_COMPANY. In my case, I've saved the file to ~/.ssh/id_rsa_work.

Step 2 - Attach the New Key

Next, login to your second GitHub account, browse to "Account Overview" and attach the new key, within the "SSH Public Keys" section. To retrieve the value of the key that you just created, return to the Terminal and type: vim ~/.ssh/id_rsa_COMPANY.pub.

Copy the entire string that is displayed, and paste this into the GitHub textarea. Feel free to give it any title you wish.

Next, because we saved our key with a unique name, we need to tell SSH about it. Within the Terminal, type: ssh-add ~/.ssh/id_rsa_COMPANY. If successful, you'll see a response of Identity Added.

Step 3 - Create a Config File

We've done the bulk of the workload; but now we need a way to specify when we wish to push to our personal account, and when we should instead push to our company account. To do so, let's create a config file.

touch ~/.ssh/config vim config

If you're not comfortable with Vim, feel free to open it within any editor of your choice. Paste in the following snippet.

Default GitHub


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

This is the default setup for pushing to our personal GitHub account. Notice that we're able to attach an identity file to the host. Let's add another one for the company account. Directly below the code above, add:

	Host github-COMPANY
	  HostName github.com
	  User git
	  IdentityFile ~/.ssh/id_rsa_COMPANY

This time, rather than setting the host to github.com, we've named it as github-COMPANY. The difference is that we're now attaching the new identity file that we created previously: id_rsa_COMPANY. Save the page and exit!

Step 4 - Try it Out

It's time to see if our efforts were successful. Create a test directory, initialize git, and create your first commit.

	git init
	git commit -am "first commit'

Login to your company account, create a new repository, give it a name of "Test," and then return to the Terminal and push your git repo to GitHub.

	git remote add origin git@github-COMPANY:Company/testing.git
	git push origin master

Note that, this time, rather than pushing to git@github.com, we're using the custom host that we create in the config file: git@github-COMPANY.

Return to GitHub, and you should now see your repository. Remember:

When pushing to your personal account, proceed as you always have. For your company account, make sure that you use git!github-COMPANY as the host.

@withcheesepls
Copy link

withcheesepls commented Dec 18, 2018

For some reason I had to change the email in the repo to show the commits in the right account.
https://help.github.com/articles/setting-your-commit-email-address-in-git/

I made a bash script to replace the github.com with the other host and then change the email to the other account

gitcloneother(){
  git clone "${1/github.com/github-COMPANY}"
  repo_name_find=$(echo "$1" | egrep -o '/.+\.git')
  #remove slash
  repo_name=$(echo "$repo_name_find" | egrep -o '[^/].+')
  # remove the '.git' and cd in that new folder
  cd "${repo_name/.git/}"
  git config user.email "COMPANY@email.com"
}

(I am not good at bash, maybe someone can do better)

I use git clone to use my primary account and gitcloneother to clone for the other account.

@gl-sergei
Copy link

You might need to add IdentitiesOnly yes if you use ssh-agent or gpg-agent to manage identities.

@emiloserdov
Copy link

emiloserdov commented Apr 17, 2019

Hello @JoaquimLey. I'm trying to set my repo to use correct ssh key, but I can't make it.

  1. I edited ~/.ssh/config file like this:
Host github-10gen
    HostName github.com
    User git
    IdentityFile ~/.ssh/new_key_file
    IdentitiesOnly yes
  1. I set remote url like this:
    git remote set-url origin git@github-10gen:10gen/ops-manager-cloudfoundry
  2. Trying
    git push origin dev
    but getting error:
ssh: Could not resolve hostname github-10gen: Name or service not known
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

What am I doing wrong?

@TyIsI
Copy link

TyIsI commented Oct 16, 2019

but getting error:

ssh: Could not resolve hostname github-10gen: Name or service not known
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

What am I doing wrong?

Just in case anyone reads this; this might be due to permissions or location.

@emiloserdov the permission for ~/.ssh should be 700, with 600 for ~/.ssh/*. In some cases, SSH gets confused about the location of ~, in which case you can test it with ssh -F ~/.ssh/config.

@JoaquimLey
Copy link
Author

Exactly, that's most likely due to permissions. Is the user you have the same as the user that has access to the repository?

@dcsan
Copy link

dcsan commented Nov 30, 2019

This didn't work for me in the end, but i realized i can use github desktop to check out from a second account, may help someone else.

@wagant
Copy link

wagant commented Jan 4, 2020

You might need to add IdentitiesOnly yes if you use ssh-agent or gpg-agent to manage identities.

It did work for me.

@MaryTWelch
Copy link

I am trying to complete this in Powershell, but I am getting the following message:
ssh-add ~/.ssh/id_rsa_work
Error connecting to agent: no such file or directory

I can see in the file explorer that my ssh keys exist and are in the .ssh directory, so I don't know why it can't recognize the location...

@JoaquimLey
Copy link
Author

Since you're running PowerShell can I assume you are using Windows?

If so the path ~/* might not work as it isn't Unix (it has been a while since I used win and/or PowerShell).

To make it simple, open the terminal and cd into your ssh key's path and try to run the command ssh-add id_rsa_work

Let me know if this works for you.

@MaryTWelch
Copy link

@JoaquimLey that seems to have worked so far.... I can't believe it was that stinkin' simple.

@mtander
Copy link

mtander commented Apr 16, 2020

I am working in Visual Studio code, and my git config is set to my work account (user.name & user.email). When I use the terminal in VS Code to try to push my branch back to the remote, I get the following result. I know it is trying to push the branch to the wrong account, but I don't know how to tell it which git account to use.
image
I want to push to my personal account, but it is trying to sign in to my work account instead.

@mtander
Copy link

mtander commented Apr 16, 2020

I FIGURED IT OUT. Sorry, I'm just excited because I've been working on this for a silly amount of time. Once I got the ssh identities added correctly as you indicated... I was able to follow the pattern emiloserdev indicated above.
git remote set-url origin CONFIGUSERNAME@HOST:GITHUBUSERNAME/REPONAME.git
and then
git push -u origin remoteBranch
(using origin/remoteBranch was giving me issues for some reason)
I think I'm going to go celebrate with more coffee :-)

@JoaquimLey
Copy link
Author

@MaryTWelch I'm glad to know you've made it work, and it is always simple after we know how to do it :p

@mtander sorry for not getting back to you in time to help you out but I'm glad you've also sorted it out :D

@VictorMarcas
Copy link

@mtander you have solved that problem for me, thank you very much

@apegineer
Copy link

Another tip to quickly test is that you can do ssh -T git@github.com and ssh -T git@github.com-COMPANY to see if the setting is already correct or not.

@ndemarco
Copy link

ndemarco commented Aug 1, 2021

Given two GitHub profiles ndemarco and nmdemarco, I have not been able to make this work. Please explain how the URL in this command is constructed: git remote add origin git@github-COMPANY:Company/testing.git

git@github-COMPANY can become git@github-ndemarco if this matches a section in the ~/.ssh/config file?
and the repo address (after the :) has to match the GitHub repo, like ndemarco/test?

I'm not understanding how Git finds the remote name git@github-ndemarco when the remote is really at git@github.com.

My file permissions are correct (~./ssh is 700, ~/.ssh/* is 600).

@TyIsI
Copy link

TyIsI commented Aug 31, 2021

@ndemarco:

I'm not understanding how Git finds the remote name git@github-ndemarco when the remote is really at git@github.com.

Assuming that nmdemarco would be your company account and ndemarco your private account. You'd generate 2 ssh keys:

  • ssh-keygen -f ~/.ssh/id_github_ndemarco (and add that to your ndemarco account)
  • ssh-keygen -f ~/.ssh/id_github_nmdemarco (and add that to your nmdemarco account)

Then you'd configure your SSH config like this:

Host github-ndemarco
 HostName github.com
 PreferredAuthentications publickey
 IdentityFile ~/.ssh/id_github_ndemarco

Host github-COMPANY
 HostName github.com
 PreferredAuthentications publickey
 IdentityFile ~/.ssh/id_github_nmdemarco

Then you can add your origin for a company repository just the way you posted it:
git remote add origin git@github-COMPANY:Company/testing.git

@ndemarco
Copy link

ndemarco commented Aug 31, 2021 via email

@karlrado
Copy link

karlrado commented Feb 1, 2022

Here's another way to approach it if your workflow is such that all of your company repositories are placed or can be placed under one (or a few) directories. This way is also "automatic" in the sense that whenever you clone a repo under the company directory, it just works. You don't have to remember to modify the origin with the git@github-COMPANY alias.

Assuming your company directory is ~/company:

  • Add the following to your ~/.gitconfig file:
[includeif "gitdir:~/company/*]
        path = ~/.gitconfig_company
  • Create the ~/.gitconfig_company file:
[core]
    sshCommand = "ssh -F ~/.ssh/config_company"
[user]
    name = <My name in the way I want it to appear in my company commits>
    email = <My company email address>
  • And finally create another SSH config file ~/.ssh/config_company:
Host github.com
        Hostname github.com
        IdentityFIle <location of my RSA SSH private key file I'm using for the company GitHub account>
        IdentitiesOnly yes
        User <My company GitHub username>

I found that I was always changing my git user.email whenever I cloned a company repository anyway and so started to use the [includeif ...] feature to deal with that. It was an easy addition to pick a separate SSH config as well. This can also be used to set other company-specific Git settings.

@TyIsI
Copy link

TyIsI commented Feb 6, 2022

@karlrado That's a beautiful solution! Thanks for sharing!

Copy link

ghost commented Mar 24, 2022

I had to remove Hostname github.com from the primary account in .ssh/config to get it working

@rcmdv
Copy link

rcmdv commented Dec 3, 2022

Thanks JoaquimLey for the hints!

One remark on this setup:

It may happen that you have another user and email configured globally.
So even when you connect via ssh to a different GitHub account you are still committing with the other user.
Check your global configuration:

git config --global --list

You can set a different local user an email per repository.
Run this in your repo to set the user for the current repository only:

git config --local user.name "homeuser"
git config --local user.email "homeuser@example.com"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment