Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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!

@dipam7
Copy link

dipam7 commented Jun 16, 2021

Is there a way to set the username and email in config too?

Extending the answer by @jamolpe, here is something that I have been using. Hope that helps.
1609126708255

After doing this, how do you ensure you are pushing with the professional git account? The personal details are configured in the global name and email

@othonreyes
Copy link

[core]
sshCommand = "ssh -i ~/.ssh/id_ed25519"

Thanks for this useful post! I just wanted to add that as of git 2.10 you can now specify the ssh command in the config so there is no need for ssh magic any longer. https://git-scm.com/docs/git-config#Documentation/git-config.txt-coresshCommand

So your git-personal.conf could look like this now.

[user]
  name = X X
  email = x@x.com
  signingkey = XXXXXXXXXX

[github]
  user = "x"

[core]
  sshCommand = "ssh -i  ~/.ssh/id_ed25519"

This reply was super helpful. I didn't need to edit the ~/.ssh/config file or change the remote url by using this solution. Now I can use plain git urls without any ssh magic.

@umairhm
Copy link

umairhm commented Jul 28, 2021

Is there a way to set the username and email in config too?

Extending the answer by @jamolpe, here is something that I have been using. Hope that helps.
1609126708255

After doing this, how do you ensure you are pushing with the professional git account? The personal details are configured in the global name and email

If you see the sequence, the professional conf is included after the personal one, so it changes the account automatically based on the git directory.

There is one caveat that I recently found is that we need to have a git directory to make this work. If I go to the root of the professional directory, which is not a git directory itself, I will get the personal account. A simple workaround for me was to run git init in the root of the professional directory. So now if I have to clone a new repo from my company's GitHub, I will be able to do so without any issue.

@zyadsherif
Copy link

Thank you

@sireesha-charyulu
Copy link

Thank you very much

@elmarsan
Copy link

My hero!

@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

@rosatamarindus
Copy link

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 ?

@heliocosta1337
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

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