Skip to content

Instantly share code, notes, and snippets.

@Jonalogy
Last active March 28, 2024 06:37
Show Gist options
  • Save Jonalogy/54091c98946cfe4f8cdab2bea79430f9 to your computer and use it in GitHub Desktop.
Save Jonalogy/54091c98946cfe4f8cdab2bea79430f9 to your computer and use it in GitHub Desktop.
Handling Multiple Github Accounts on MacOS

Handling Multiple Github Accounts on MacOS

The only way I've succeeded so far is to employ SSH.

Assuming you are new to this like me, first I'd like to share with you that your Mac has a SSH config file in a .ssh directory. The config file is where you draw relations of your SSH keys to each GitHub (or Bitbucket) account, and all your SSH keys generated are saved into .ssh directory by default. You can navigate to it by running cd ~/.ssh within your terminal, open the config file with any editor, and it should look something like this:

Host *
 AddKeysToAgent yes
 UseKeyChain yes
 IdentityFile ~/.ssh/id_rsa
 ForwardAgent yes

Assuming you've got 2 github accounts, for work and play, lets get your Mac to "register" them. To do that that you'll need to create SSH key pairs for each account. If you have already setup your Mac to SSH with one of them, or check if you have one, continue on with the following for the second account.

1. Creating the SSH keys. For each SSH key pairs:

  • run ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

  • You'll be prompted: "Enter a file in which to save the key" and the suggested default filename would be id_rsa. This filename will be used for your SSH private and public keys so remember to make it unique, eg. user-1, user-2. This step will generate both the private and public keys, user-1 + user-1.pub , user-2 + user-2.pub respectively.

  • GitHub has this step in detail. We're not adding the keys to the ssh-agent.

2. Register your keys to the respective GitHub accounts.

  • Follow these steps to do so.

3. Head back over to the SSH config file at ~/.ssh and amend accordingly to:

#user1 account
Host github.com-user1
   HostName github.com
   User git
   IdentityFile ~/.ssh/github-user1
   IdentitiesOnly yes

#user2 account
Host github.com-user2
   HostName github.com
   User git
   IdentityFile ~/.ssh/github-user2
   IdentitiesOnly yes

Replace user1 or user2 with your GitHub usernames/identification-handlers

4. Go ahead to git clone your respective repository

git clone git@github.com-user1:user1/your-repo-name.git your-repo-name_user1

5. Configure your git identity:

  • Open up local git config using git config --local -e and add:
[user]
    name = user1
    email = user1@gmail.com

6. Ensure your remote url is in the right format e.g: git@github.com-user1:user1/your-repo-name.git your-repo-name_user1

  • You either run git remote set-url origin git@github.com-user1:user1/your-repo-name.git your-repo-name_user1
  • Or amend your remote ssh-url in your local git config file:
 [remote "origin"] 
       url = git@github.com-user1:user1/your-repo-name.git
       fetch = +refs/heads/*:refs/remotes/origin/*

Now you can git actions (pull/push/fetch...etc) all you like!

Resources:

Special thanks to @pbuditi for your help!

@loocurse
Copy link

Thank you very much :D

@rotoshine
Copy link

Thank you!!!

@tw-yshuang
Copy link

tw-yshuang commented Dec 14, 2021

I create a CLI command to handle this!
Checkout my repo~~
This repo uses ssh-agent to switch your ssh account.

Git_SSH-Account_Switch

A CLI tool can switch an ssh account to your current shell. You will easily switch to your git account & ssh key when using the server, and using your account to manipulate the project on the server.

Installation

$ bash ./setup.sh

it will add some code in your profile & $logout_profile, and setup git-acc & .gitacc on the $HOME.
file:

git-acc.sh -> $HOME/.git-acc, git-acc function.
.gitacc -> $HOME/.gitacc, save info. that regist on git-acc.

Control

        +---------------+
        |    git-acc    |
        +---------------+

SYNOPSIS

  git-acc [account]|[option]

OPTIONS

  [account]               use which accounts on this shell, type the account name that you register.
  -h, --help              print help information.
  -add, --add_account     build git_account info. & ssh-key.
      -t, --type          ssh-key types, follow `ssh-keygen` rule, 
                          types: dsa | ecdsa | ecdsa-sk | ed25519 | ed25519-sk | rsa(default)
  -rm, --remove_account   remove git_account info. & ssh-key from this device
  -out, --logout          logout your current ssh-acc.


EXAMPLES

  $ git-acc tw-yshuang

@NateAtNTS
Copy link

This is what I needed. Thanks!

@douglas-oliveira-tc
Copy link

Worked like a charm, buddies!!! You guys rock!

@TraeDbot
Copy link

Much thanks ! 🔩⚡️

@bhatia-siddharth
Copy link

ssh-add ~/.ssh/

worked

@giuseppe-grasso
Copy link

giuseppe-grasso commented May 10, 2022

I followed the instructions outlined above about a month ago, and everything worked correctly.

Now, after a month, I went back to make some local changes and tried to push using my-secondary-account.
However, I get the following message "Please make sure you have the correct access rights
and the repository exists."

Now, if I run:

git remote -v

I get:

origin	git@github.com-my-secondary-account:my-secondary-account/my-repo.git (fetch)
origin	git@github.com-my-secondary-account:my-secondary-account/my-repo.git (push)

which should be fine I guess.

Also, running

git config user.name
git config user.email

returns my-secondary-account and my-secondary-account-email

Lastly, opening the repo config file via

git config --local -e

I get:

[remote "origin"]
        url = git@github.com-my-secondary-account:my-secondary-account/my-repo.git
        fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
        remote = origin
        merge = refs/heads/master
[user]
    name = my-secondary-account
    email = my-secondary-account-email

To me, these look like the exact settings that I had managed to tune, thanks to this guide, to make everything work. I fail to see where the problem is.

I would like to stress that the error message that I get now is different to what I was getting prior to setting the local config file right thanks to this guide, which was:

ERROR: Permission to my-secondary-account/my-repo.git denied to my-primary-account.
fatal: Could not read from remote repository.

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

Now, I either get:

ssh: connect to host github.com port 22: Operation timed out
fatal: Could not read from remote repository.

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

or simply:

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

If you can help me to fix this, I'd be extremely grateful. Thanks!

@iamtodor
Copy link

iamtodor commented Jul 5, 2022

For me this command git remote set-url origin git@github.com-user1:user1/your-repo-name.git your-repo-name_user1 creates a dir your-repo-name_user1 and it does not use a user1 profile

@rosandus
Copy link

rosandus commented Jul 6, 2022

I followed the instructions outlined above about a month ago, and everything worked correctly.

Now, after a month, I went back to make some local changes and tried to push using my-secondary-account. However, I get the following message "Please make sure you have the correct access rights and the repository exists."

Now, if I run:

git remote -v

I get:

origin	git@github.com-my-secondary-account:my-secondary-account/my-repo.git (fetch)
origin	git@github.com-my-secondary-account:my-secondary-account/my-repo.git (push)

which should be fine I guess.

Also, running

git config user.name
git config user.email

returns my-secondary-account and my-secondary-account-email

Lastly, opening the repo config file via

git config --local -e

I get:

[remote "origin"]
        url = git@github.com-my-secondary-account:my-secondary-account/my-repo.git
        fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
        remote = origin
        merge = refs/heads/master
[user]
    name = my-secondary-account
    email = my-secondary-account-email

To me, these look like the exact settings that I had managed to tune, thanks to this guide, to make everything work. I fail to see where the problem is.

I would like to stress that the error message that I get now is different to what I was getting prior to setting the local config file right thanks to this guide, which was:

ERROR: Permission to my-secondary-account/my-repo.git denied to my-primary-account.
fatal: Could not read from remote repository.

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

Now, I either get:

ssh: connect to host github.com port 22: Operation timed out
fatal: Could not read from remote repository.

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

or simply:

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

If you can help me to fix this, I'd be extremely grateful. Thanks!

Did you make sure that your sshCommand in your local repo is correct? If not, you could try to run git config core.sshCommand "ssh -i /path/to/key"? then you'll be asked about adding your key fingerprint (e.g 'SHA256:[key]') to the list of know hosts. Afterward, you could check git remote show origin to make sure you have the correct access rights now.

@peppegrass
Copy link

thanks for all the suggestions, now it is working

@gamgyul
Copy link

gamgyul commented Aug 7, 2022

thanks for the post. It really helped me

@lin-nguyen
Copy link

thanks for all suggestions

@sushilatlabs
Copy link

Thanks a lot.

@devsandeshnaik
Copy link

Very helpful thanks a lot.

@bky373
Copy link

bky373 commented Oct 29, 2022

Thanks a lot. :)

@ashutoshsinghparmar
Copy link

Thanks a lot... a long pending item in my to-do, today finally completed.

@jamolpe
Copy link

jamolpe commented Nov 2, 2022

Just a thing I noticed (not sure if something have changed) a few weeks ago this solution seems to stop working propertly and main .gitconfig user was used for everything. In order to fix that what I did is just move the [user] section in the main gitconfig to the top.

@lisachacho
Copy link

Thanks Jonalogy!!

@n8sabes
Copy link

n8sabes commented Jan 2, 2023

Thanks @Jonalogy!

Incredibly useful -- Thanks for taking the time to figure this out and share it.

@Trangbn
Copy link

Trangbn commented Jan 16, 2023

I followed the guide. However it always accept the first relevant_ssh_key when it's added. The second added is always ERROR repository not found. Could you advise on this ?

@heliocosta-dev
Copy link

🚀🎉

@iamtodor
Copy link

I was able to make it happen only with multiple .gitconfig, that I configured for multiple dirs https://superuser.com/questions/232373/how-to-tell-git-which-private-key-to-use/912281#912281 such as

[includeIf "gitdir:~/PROJ1/"]
    path = ~/.gitconfig-proj1


[includeIf "gitdir:~/PROJ2/"]
    path = ~/gitconfig-proj2

A very decent guide is here https://superuser.com/questions/232373/how-to-tell-git-which-private-key-to-use/912281#912281

@mwritter
Copy link

mwritter commented Mar 16, 2023

Sometime adding the key was not solving it for me. So i started following this sequentially. It gives more consistent result.

# list all the SSH keys attached to the ssh-agent
$ ssh-add -l
# removes all ssh entries from the ssh-agent                             
$ ssh-add -D
# Adds the relevant ssh key  
$ ssh-add ~/.ssh/relevant_ssh_key

🙌 This seems to be the easiest method for me - Thanks!
I added an alias in my rc file to make this even easier 😆

# Alias for switching git accounts
alias git_user1='ssh-add -D && ssh-add ~/.ssh/user1_id'
alias git_user2='ssh-add -D && ssh-add ~/.ssh/user2_id'

now to switch accounts I just run git_user1 or git_user2

@alesalv
Copy link

alesalv commented Apr 28, 2023

I have similar problems mentioned here and there in the comments, in a two users setup:

  • few months ago it stopped working
  • when I add both keys then only one is accepted, the second one gives errors

The only solution for me is to always remove all of them (ssh-add -D) and then add only the one I'm using at the moment ... I've also added aliases, but it's quite annoying

@ansarisufiyan777
Copy link

I create a CLI command to handle this! Checkout my repo~~ This repo uses ssh-agent to switch your ssh account.

Git_SSH-Account_Switch

A CLI tool can switch an ssh account to your current shell. You will easily switch to your git account & ssh key when using the server, and using your account to manipulate the project on the server.

Installation

$ bash ./setup.sh

it will add some code in your profile & $logout_profile, and setup git-acc & .gitacc on the $HOME. file:

git-acc.sh -> $HOME/.git-acc, git-acc function.
.gitacc -> $HOME/.gitacc, save info. that regist on git-acc.

Control

        +---------------+
        |    git-acc    |
        +---------------+

SYNOPSIS

  git-acc [account]|[option]

OPTIONS

  [account]               use which accounts on this shell, type the account name that you register.
  -h, --help              print help information.
  -add, --add_account     build git_account info. & ssh-key.
      -t, --type          ssh-key types, follow `ssh-keygen` rule, 
                          types: dsa | ecdsa | ecdsa-sk | ed25519 | ed25519-sk | rsa(default)
  -rm, --remove_account   remove git_account info. & ssh-key from this device
  -out, --logout          logout your current ssh-acc.


EXAMPLES

  $ git-acc tw-yshuang

This extension is seems to only for Linux, anyone succeeded in Mac?

@tw-yshuang
Copy link

Hi @ansarisufiyan777, I'm the author of this extension. I think it can be functional on the MBP & Ubuntu because I'm using this tool on both platforms. What's the problem you met?

@tiennsloit
Copy link

Thanks a lot!

@kirstenthedev
Copy link

Hi, thanks so much for the guide! It's always my go to when setting up.
Just wanted to check in if there's a way I can configure my git users to automatically switch users when busy on either work projects or person work. Sometimes my personal user is able to push work to my work repo's which I don't want

@palluvageria
Copy link

Thank you so much! this really helped

@kwam1na
Copy link

kwam1na commented Jun 14, 2023

the hero we needed but don't deserve

@DLoBoston
Copy link

This is helpful again, years later. Also, LOVE @kwam1na comment. Exactly!

@tamili2i
Copy link

What if the repo is in the organization how to set the remote URL for it.
git@github.com-my-secondary-account:organizationname/my-repo.git
is this correct?

@tsoli0321
Copy link

@tamili2i - Your line worked for me. I keep forgetting how to do this every time I have a new org repo to clone locally.
Thanks!

@Manishiiitbhopal23
Copy link

currently, I am working with GitHub let's assume with the email: xyz@gmail.com and I have another GitHub with an email linked with abc@gmail.com How I can work on both GitHub accounts with the same terminal Please suggest!

@tamili2i
Copy link

tamili2i commented Dec 8, 2023

@Manishiiitbhopal23

Configure ssh for two accounts

#user1 account
Host github.com-xyz
   HostName github.com
   User git
   IdentityFile ~/.ssh/github-user1
   IdentitiesOnly yes

#user2 account
Host github.com-abc
   HostName github.com
   User git
   IdentityFile ~/.ssh/github-user2
   IdentitiesOnly yes

Clone Repositorys like below

Repository1 - git clone git@github.com-xyz:user1/your-repo-name.git your-repo-name_user1
Repository2 - git clone git@github.com-abc:user2/your-repo-name.git your-repo-name_user2

@hile
Copy link

hile commented Dec 11, 2023

There is another way to do this with SSH: create SSH configuration aliases for the hosts to define separate keys and change the origin URLs in SSH string to use these alias hosts.

In .ssh/config

Host personal.github.com
  User personalid
   IdentityFile~/ .ssh/personal-ssh-key
   HostName github.com
Host work.github.com
  User workaccount
  IdentityFile ~/.ssh/work-ssh-key
  HostName github.com

And then change origin URL in repo config to use git@personal.github.com:whatever or git@work.github.com:somethingelse kind of URLs. The git commands don't do DNS lookups and SSH resolves the alias names for you with correct key.

@varzhonglei
Copy link

varzhonglei commented Jan 11, 2024

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