Skip to content

Instantly share code, notes, and snippets.

@rahularity
Last active July 1, 2024 13:02
Show Gist options
  • Save rahularity/86da20fe3858e6b311de068201d279e3 to your computer and use it in GitHub Desktop.
Save rahularity/86da20fe3858e6b311de068201d279e3 to your computer and use it in GitHub Desktop.
How To Work With Multiple Github Accounts on your PC

How To Work With Multiple Github Accounts on a single Machine

Let suppose I have two github accounts, https://github.com/rahul-office and https://github.com/rahul-personal. Now i want to setup my mac to easily talk to both the github accounts.

NOTE: This logic can be extended to more than two accounts also. :)

The setup can be done in 5 easy steps:

Steps:

  • Step 1 : Create SSH keys for all accounts
  • Step 2 : Add SSH keys to SSH Agent
  • Step 3 : Add SSH public key to the Github
  • Step 4 : Create a Config File and Make Host Entries
  • Step 5 : Cloning GitHub repositories using different accounts

Step 1

Create SSH keys for all accounts

First make sure your current directory is your .ssh folder.

     $ cd ~/.ssh

Syntax for generating unique ssh key for ann account is:

     ssh-keygen -t rsa -C "your-email-address" -f "github-username"

here,

-C stands for comment to help identify your ssh key

-f stands for the file name where your ssh key get saved

Now generating SSH keys for my two accounts

     ssh-keygen -t rsa -C "my_office_email@gmail.com" -f "github-rahul-office"
     ssh-keygen -t rsa -C "my_personal_email@gmail.com" -f "github-rahul-personal"

Notice here rahul-office and rahul-work are the username of my github accounts corresponding to my_office_email@gmail.com and my_personal_email@gmail.com email ids respectively.

After entering the command the terminal will ask for passphrase, leave it empty and proceed.

Passphrase Image

Now after adding keys , in your .ssh folder, a public key and a private will get generated.

The public key will have an extention .pub and private key will be there without any extention both having same name which you have passed after -f option in the above command. (in my case github-rahul-office and github-rahu-personal)

Added Key Image


Step 2

Add SSH keys to SSH Agent

Now we have the keys but it cannot be used until we add them to the SSH Agent.

     ssh-add -K ~/.ssh/github-rahul-office
     ssh-add -K ~/.ssh/github-rahul-personal

You can read more about adding keys to SSH Agent here.


Step 3

Add SSH public key to the Github

For the next step we need to add our public key (that we have generated in our previous step) and add it to corresponding github accounts.

For doing this we need to:

1. Copy the public key

 We can copy the public key either by opening the github-rahul-office.pub file in vim and then copying the content of it.
     vim ~/.ssh/github-rahul-office.pub
     vim ~/.ssh/github-rahul-personal.pub

OR

We can directly copy the content of the public key file in the clipboard.

     pbcopy < ~/.ssh/github-rahul-office.pub
     pbcopy < ~/.ssh/github-rahul-personal.pub

2. Paste the public key on Github

  • Sign in to Github Account
  • Goto Settings > SSH and GPG keys > New SSH Key
  • Paste your copied public key and give it a Title of your choice.

OR


Step 4

Create a Config File and Make Host Entries

The ~/.ssh/config file allows us specify many config options for SSH.

If config file not already exists then create one (make sure you are in ~/.ssh directory)

     touch config

The commands below opens config in your default editor....Likely TextEdit, VS Code.

     open config

Now we need to add these lines to the file, each block corresponding to each account we created earlier.

     #rahul-office account
     Host github.com-rahul-office
          HostName github.com
          User git
          IdentityFile ~/.ssh/github-rahul-office

     #rahul-personal account
     Host github.com-rahul-personal
          HostName github.com
          User git
          IdentityFile ~/.ssh/github-rahul-personal

Step 5

Cloning GitHub repositories using different accounts

So we are done with our setups and now its time to see it in action. We will clone a repository using one of the account we have added.

Make a new project folder where you want to clone your repository and go to that directory from your terminal.

For Example: I am making a repository on my personal github account and naming it TestRepo Now for cloning the repo use the below command:

    git clone git@github.com-{your-username}:{owner-user-name}/{the-repo-name}.git

    [e.g.] git clone git@github.com-rahul-personal:rahul-personal/TestRepo.git

Finally

From now on, to ensure that our commits and pushes from each repository on the system uses the correct GitHub user — we will have to configure user.email and user.name in every repository freshly cloned or existing before.

To do this use the following commands.

     git config user.email "my_office_email@gmail.com"
     git config user.name "Rahul Pandey"
     
     git config user.email "my-personal-email@gmail.com"
     git config user.name "Rahul Pandey"

Pick the correct pair for your repository accordingly.

To push or pull to the correct account we need to add the remote origin to the project

     git remote add origin git@github.com-rahul-personal:rahul-personal
     
     git remote add origin git@github.com-rahul-office:rahul-office

Now you can use:

     git push
     
     git pull

P.S:
If this gist has been helpful to you, kindly consider leaving a star.
If you'd like, let's connect on LinkedIn and build a supportive community together.

@iancooper4321
Copy link

Can someone please help me figure out what is going wrong? I yet again am having trouble. I had this all set up, but now I am getting permission errors and git keeps trying to use my work user.

ERROR: Permission to iankingcoop/powder_alert.git denied to XXX_WORK_USER_XXXX.
fatal: Could not read from remote repository.

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

@VictoriousRaptor
Copy link

VictoriousRaptor commented Feb 8, 2023

Can someone please help me figure out what is going wrong? I yet again am having trouble. I had this all set up, but now I am getting permission errors and git keeps trying to use my work user.

ERROR: Permission to iankingcoop/powder_alert.git denied to XXX_WORK_USER_XXXX.
fatal: Could not read from remote repository.

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

Set your remote url to like git@your-username:{owner-user-name}/{the-repo-name}.git. It works for me.

@iancooper4321
Copy link

Thanks for helping. I did get this to work.

setting the url to
git@github.com-<my_username>:{owner-user-name}/{the-repo-name}.git

This process is so painful in general. Adding the right URL, SSH forgetting certain keys, and needing to change the url so that it contains the hostname and not just @github.com.... so frustrating. I blame git.

@savaryna
Copy link

Hey! Having to deal with the same problem, inspired by posts like yours and tired of repeating the steps every time I want to add a new account or switch machines, I created this npm package @savaryna/git-add-account (maybe a bit too much I know), but it does all that automatically. Maybe some of you guys can try it out and let me know how did it work for you! 🙇

You can just run npx @savaryna/git-add-account, enter your details and done! 🌟

@ryan-bowers-vectorsolutions

This is awesome. This should be the defacto ssh tutorial on githubs help section. Works, (for me) and makes more sense than the other tutorials even for single accounts using ssh. Bookmarked this page under "This is the way (ssh github)"

@ivan-toriya
Copy link

@rahularity

-  ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
+  ssh-keygen -t ed25519 -C "your_email@example.com"

New recommended way by GitHub is to use ed25519 instead of rsa-4096.

@saadnvd1
Copy link

Thank you!

@saadnvd1
Copy link

I also realized that if you want to keep your personal as the default, you can change your ~/.ssh/config to resemble this:

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

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

@mahyar-osn
Copy link

This was great thank you!

@luciano-work
Copy link

Thank you ;)

@ztaylor797
Copy link

Just dropping this here for anyone else that runs into it.

If your GitHub org has SSO enabled, there is an additional step that must be taken.
If not done, you will run into this error:

ERROR: The `Foo' organization has enabled or enforced SAML SSO. To access
this repository, you must use the HTTPS remote with a personal access token
or SSH with an SSH key and passphrase
that has been authorized for this organization. Visit
https://docs.github.com/articles/authenticating-to-a-github-organization-with-saml-single-sign-on/ for more information.

fatal: Could not read from remote repository.

Please make sure you have the correct access rights

Per the doc link above, you just need to go to your SSH keys page and click Configure SSO next to the SSH key you just added. Then select the proper Organization and click Authorize.

image

@zayedupal
Copy link

I was facing with user name issue and this video solved the problem:
https://www.youtube.com/watch?v=6lA0oPoFCAE&ab_channel=JcMiron

@danielbped
Copy link

awesome tutorial, thanks a lot!

@jmantonellini
Copy link

Thank you! Great tutorial

@kopstill
Copy link

Great, thanks!

@leohalley
Copy link

Thanks !!

@NSVEGUR
Copy link

NSVEGUR commented Apr 14, 2023

Thanks man!

@RitamAgrawal
Copy link

Well elaborated! a very helpful one. Thank you.

@rapsknight999
Copy link

rapsknight999 commented Apr 19, 2023

NVM I got it, had to git remote set-url origin instead of adding it, since when a repo is cloned it automatically adds a remote origin.

Did you change the URL @iankingcoop

@Harsha2311
Copy link

Thanks for step-by-step guide

@shashikanthM1
Copy link

this is cool

@mpersonbio
Copy link

mpersonbio commented May 9, 2023

Just dropping this here for anyone else that runs into it.

If your GitHub org has SSO enabled, there is an additional step that must be taken. If not done, you will run into this error:

ERROR: The `Foo' organization has enabled or enforced SAML SSO. To access
this repository, you must use the HTTPS remote with a personal access token
or SSH with an SSH key and passphrase
that has been authorized for this organization. Visit
https://docs.github.com/articles/authenticating-to-a-github-organization-with-saml-single-sign-on/ for more information.

fatal: Could not read from remote repository.

Please make sure you have the correct access rights

Per the doc link above, you just need to go to your SSH keys page and click Configure SSO next to the SSH key you just added. Then select the proper Organization and click Authorize.

image

YES Thanks. Spent about two days trying to get this working and I had this same issue. I feel like there should be a prompt to ask the user to authorize when a key is added.

@jelilio
Copy link

jelilio commented May 28, 2023

Thanks man!

@pardeepenverx
Copy link

My configuration working fine with two accounts added, after couple of days have added another account configuration in the same way mentioned above.
Now only new added account os working fine not the previous one's any help?

@MamathaYarramaneni
Copy link

@pardeepenverx Try adding the corresponding remote for the local repository.

@rostfrei
Copy link

It works but not with submodules. Submodule URLs are baked into the repository .gitmodules file.

@yeam-10
Copy link

yeam-10 commented Jul 23, 2023

Thanks you !!

@badsyntaxx
Copy link

Is there a not retarded way to work with multiple github accounts?

@sky1095
Copy link

sky1095 commented Jul 29, 2023

when I tried git push -u origin main in my second github account

this error message appears

ERROR: Repository not found.
fatal: Could not read from remote repository.

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

can you help me?

I was having the same issue, and this is how I fixed it

first checked if my SSH connection was working or not using this command:
ssh -T git@github.com-{user.name}

it showed me a different account username, which helped me understand I wans't using the proper alias. Then used this command to add the key
ssh-add ~/.ssh/{ssh-key-name} and the used the above command to confirm its using the right alias now.
And it worked!

@oddantfr
Copy link

oddantfr commented Aug 7, 2023

this is work too, it more normal

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

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

Please remove your comment, it is misleading people. Indeed you shouldn't do that if you want to manage several accounts.

@paiman-truetale
Copy link

paiman-truetale commented Aug 22, 2023

@oddantfr
The HostName must be different for now when you clone a repo it will use the default git account,

@AyemunHossain
Copy link

Is there a not retarded way to work with multiple github accounts?

Right

@preetmyob
Copy link

thank you for clear instructions

@PreetSangha
Copy link

Yes (indeed) thank you from my other account too :-D

@DeveshPareek27
Copy link

Great explanation man

@huuco
Copy link

huuco commented Sep 7, 2023

💯

@NasimNoble
Copy link

when accessing the repository on one of the accounts, it constantly asks to enter passphrase, for some reason there is no such problem on the second account. Maybe someone has faced the same problem?

@anteromano
Copy link

Hi, I think using separate directories (one personal and one for work) each with a separate.gitconfig is more convenient as you only need to set it up once and reuse it for all projects inside those dirs.
Explained, for example, here: https://dev.to/equiman/how-to-use-multiple-users-with-git-2e9l

@The-Next-Movement
Copy link

The-Next-Movement commented Sep 13, 2023

Thank you.

By the way, you'll need an authentication when configuring or using for the first time the new account(s).
With personal token in settings>developer settings>tokens you'll be able to authenticate the account in the git cli, and when you push if a password is asked just copy paste the token.

@BaconZhou
Copy link

Thanks!

@VitaliiGBunakov
Copy link

Awesome "clean and clear" tutorial! Wery helpful!

@Yoti-Olive
Copy link

Lovely! Thanks a lot

@Drakot
Copy link

Drakot commented Oct 17, 2023

It stopped working when updating MacOS Sonoma 14.0
anyone had the same issue?

@jeremycopinlm
Copy link

Thanks a lot, very useful

@oddantfr
Copy link

oddantfr commented Oct 29, 2023

@paiman-truetale

Yes that's why I asked the person who wrote the comment to remove it, it defeated the purpose of what we are trying to do here.

@oddantfr
Copy link

I wanted to add
You can use

git config --global user.name "..."
git config --global user.email "..."

to set the default settings when you create a new repo, I think it's important to know it if you want to set a default.

@siddrcCodefluenceTech
Copy link

one quick note for myself
do not forget to change git config user.name and git config user.email

@jmorales-hu
Copy link

Thanks you so much!

@vanithaganeshan
Copy link

vanithaganeshan commented Nov 22, 2023

help me out : : C:\Users\Yugajeevi KV\my_sample_repository1>git clone git@github.com:myname/my_sample_repository1.git
Cloning into 'my_sample_repository1'...
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

@kritikjain9
Copy link

Hi, I think using separate directories (one personal and one for work) each with a separate.gitconfig is more convenient as you only need to set it up once and reuse it for all projects inside those dirs. Explained, for example, here: https://dev.to/equiman/how-to-use-multiple-users-with-git-2e9l

Thanks for this!

@seicke
Copy link

seicke commented Dec 5, 2023

Hi, I think using separate directories (one personal and one for work) each with a separate.gitconfig is more convenient as you only need to set it up once and reuse it for all projects inside those dirs. Explained, for example, here: https://dev.to/equiman/how-to-use-multiple-users-with-git-2e9l

Thanks for sharing!

@Sajon5271
Copy link

Sajon5271 commented Jan 1, 2024

For anyone having trouble getting timed out while testing with ssh -T git@github.com-{-} or cloning, you might want to change the HostName and and add a Port, like these:

Host github.com-office
     HostName ssh.github.com
     User git
     IdentityFile ~/.ssh/github-office
     Port 443
     
#Personal account
Host github.com-personal
    HostName ssh.github.com
    User git
    IdentityFile ~/.ssh/github-personal
    Port 443

@clarkbrendenj
Copy link

clarkbrendenj commented Jan 15, 2024

This still requires you to clone your repository?
I have been struggling with this and tried some of these complicated solutions with ssh keys. Not sure if there is an advantage to those solutions but for me I did not want to have to clone my repository.

I found this solution (https://dev.to/hashcode01/add-a-second-remote-origin-to-git-35a7#:~:text=To%20add%20a%20second%20remote,remote%20origins%20for%20the%20repository.) to be the easiest where you just add a second remote and then push to both:

To add a second remote origin to Git and push changes to two repositories on GitHub, you can follow these steps:

Open your terminal or command prompt and navigate to the local Git repository that you want to push to two repositories. Use the git remote -v command to list the existing remote origins for the repository. You should see something like this:


$ git remote -v
origin  https://github.com/username/repo.git (fetch)
origin  https://github.com/username/repo.git (push)

Use the git remote add command to add a second remote origin to the repository. For example, if you want to add a remote origin named "second" with the URL https://github.com/username/second-repo.git, you can use the following command:

$ git remote add second https://github.com/username/second-repo.git

Use the git remote -v command again to confirm that the new remote origin has been added:


$ git remote -v
origin  https://github.com/username/repo.git (fetch)
origin  https://github.com/username/repo.git (push)
second  https://github.com/username/second-repo.git (fetch)
second  https://github.com/username/second-repo.git (push)

Make any changes to your local Git repository and commit them using the git commit command.

Use the git push command to push your changes to both remote origins. To push to both origins at once, you can use the --all option:

$ git push --all

This will push all branches to both remote origins. Alternatively, you can specify a specific branch to push to both origins:

$ git push origin branch-name
$ git push second branch-name

@rileyhemp
Copy link

Legend thank you

@zanonjonas-codes
Copy link

zanonjonas-codes commented Feb 5, 2024

A better way IMO

I created one ssh key for each account like in this gist.
Then used this to have different .gitconfig files (global, work, personal): https://dev.to/equiman/how-to-use-multiple-users-with-git-2e9l
Tks @anteromano

And in each "local" (work/personal) .gitconfig I added:

[core]
    sshCommand = ssh -i ~/.ssh/id_ed25519_personal -F /dev/null
[core]
    sshCommand = ssh -i ~/.ssh/id_ed25519_work -F /dev/null

Now I just need to git pull and push and will go to where I want depending the parent directory I am.
I think it's better.

@zanonjonas-codes
Copy link

zanonjonas-codes commented Feb 5, 2024

@badsyntaxx I think this way is less retarded xD

@darguelles-am
Copy link

Modify your ~/.gitconfig to avoid changing origins

[url "git@github.com-company:company_github_account/"]
    insteadOf = git@github.com:company_github_account/

@RabeezRiaz
Copy link

A better way IMO

I created one ssh key for each account like in this gist. Then used this to have different .gitconfig files (global, work, personal): https://dev.to/equiman/how-to-use-multiple-users-with-git-2e9l Tks @anteromano

And in each "local" (work/personal) .gitconfig I added:

[core]
    sshCommand = ssh -i ~/.ssh/id_ed25519_personal -F /dev/null
[core]
    sshCommand = ssh -i ~/.ssh/id_ed25519_work -F /dev/null

Now I just need to git pull and push and will go to where I want depending the parent directory I am. I think it's better.

This is the way. Set this up just now and it works fantastically. Only thing to keep in mind is that I need to create my random projects in my specified 'personal work' folder and not throw them on the desktop; which all things considered is a bonus advantage of this method.

@melkishengue
Copy link

A better way IMO

I created one ssh key for each account like in this gist. Then used this to have different .gitconfig files (global, work, personal): https://dev.to/equiman/how-to-use-multiple-users-with-git-2e9l Tks @anteromano

And in each "local" (work/personal) .gitconfig I added:

[core]
    sshCommand = ssh -i ~/.ssh/id_ed25519_personal -F /dev/null
[core]
    sshCommand = ssh -i ~/.ssh/id_ed25519_work -F /dev/null

Now I just need to git pull and push and will go to where I want depending the parent directory I am. I think it's better.

Awesome, works like a charm! thank you

@clarkbrendenj
Copy link

A better way IMO

I created one ssh key for each account like in this gist. Then used this to have different .gitconfig files (global, work, personal): https://dev.to/equiman/how-to-use-multiple-users-with-git-2e9l Tks @anteromano

And in each "local" (work/personal) .gitconfig I added:

[core]
    sshCommand = ssh -i ~/.ssh/id_ed25519_personal -F /dev/null
[core]
    sshCommand = ssh -i ~/.ssh/id_ed25519_work -F /dev/null

Now I just need to git pull and push and will go to where I want depending the parent directory I am. I think it's better.

I might be misunderstanding this method but doesn't this also require a clone of each project? One in each directory (work/personal) each with its own .gitconfig file?

@Pipetr
Copy link

Pipetr commented Mar 13, 2024

Awesome, nice, and clear, thanks this helps me a lot!

@jabafett
Copy link

jabafett commented Jun 1, 2024

literally just use a bash script to kill and start ssh agent then reconnect and change your git config values....you can even make one script to ask which account to use but i am just using two different scripts

@rafaelcascalho
Copy link

Great guide man! Thanks

@davepatterson
Copy link

This post was very helpful but on my mac I also needed to add a few alias commands to my shell profile in order to smoothly change company/personal git.

company git

alias u_git='git -c user.name="David Max" -c user.email="name@company.com"'

personal git

alias p_git='git -c user.name="David Max" -c user.email="davidmax@gmail.com"'

refresh ssh (sometime needs to be called when swapping between different gits)

alias r_ssh='eval "$(ssh-agent -s)"'

Then, for example, you can easily pull from your personal git using p_git pull.

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