Skip to content

Instantly share code, notes, and snippets.

@Jonalogy
Last active December 11, 2024 07:52
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 "[email protected]"

  • 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 [email protected]: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 = [email protected]

6. Ensure your remote url is in the right format e.g: [email protected]:user1/your-repo-name.git your-repo-name_user1

  • You either run git remote set-url origin [email protected]:user1/your-repo-name.git your-repo-name_user1
  • Or amend your remote ssh-url in your local git config file:
 [remote "origin"] 
       url = [email protected]: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!

@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.
[email protected]: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: [email protected] and I have another GitHub with an email linked with [email protected] 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 [email protected]:user1/your-repo-name.git your-repo-name_user1
Repository2 - git clone [email protected]: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 [email protected]:whatever or [email protected]: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

@htazad
Copy link

htazad commented Jun 29, 2024

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 โœ…

This is the easiest way I've found and it works! Thanks @mwritter for posting it <3

@rehanqasimk
Copy link

So, when we setup github account initially i.e Accout-01, we are redirected to browser OAuth based authication. So, if we follow all the above steps, now we two accounts i.e. Account-01 and Account-2, now even after switching our profile to Account-02, one is unable to pull private repo from Account-02.

@poleodevfe
Copy link

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 โœ…

This work for me, thanks pal!

@sundar-karpura
Copy link

Most comprehensive material that I have seen so far. Thank you.

@mellumeriktest
Copy link

Amazing instructions. Saved me a lot of time. Thank you.

@benji-panda
Copy link

benji-panda commented Nov 22, 2024

Some clarity on the ~/.ssh/config file:

# personal
Host github.com-benhunt-io 	# <- This is just an alias name you chose
	HostName github.com 	# <- This is the actual host to connect to
	User git				# <- Username github uses for all ssh connections
	IdentityFile ~/.ssh/id_rsa_ben # <- SSH key to use
	IdentitiesOnly yes # <- Only use specified key
	
# Git uses ssh to communicate with GitHub. When you set your remote url, you can use the alias name instead of the actual host name.
# Git will translate the alias name,  github.com-benhunt-io, to the actual host name, github.com, and use the SSH key you specified.

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