August 14, 2019

How to Easily Switch Between Different Accounts within Github (or Bitbucket or GitLab) for MacOS or Ubuntu

If you have multiple accounts within Github (or Bitbucket or GitLab) and private repos, it is sometimes necessary to switch between the accounts to do whatever git things that you need to do.

Here's how you can switch easily.

1. SSH Keys Setup

Assuming we have 2 Github accounts, let's setup the 2 different keys:

> ssh-keygen -t rsa -b 4096 -C "[email protected]"
> ssh-keygen -t rsa -b 4096 -C "[email protected]"

Save the 2 keys in separate locations as such:

> /home/user/.ssh/id_rsa_first
> /home/user/.ssh/id_rsa_second

Then add them to SSH Agent:

> eval "$(ssh-agent -s)"
> ssh-add /home/user/.ssh/id_rsa_first
> ssh-add /home/user/.ssh/id_rsa_second

Finally, add the 2 keys to your respective Github accounts. You may follow Github's detailed guide on this.

2. Setup SSH Config

We are going to differentiate different logins with the SSH Config file.

nano ~/.ssh/config

Add the following lines into your config file:

Host github1
	User git
	IdentityFile ~/.ssh/id_rsa_first

Host github2
	User git
	IdentityFile ~/.ssh/id_rsa_second

3. Testing Our New Git

Now that we are all setup, it's easy to use different keys. Noticed how we have github1 and github2 setup in the config file earlier? This is the key.

For all your future operations, replace with either github1 or github2 and SSH will use the correct credentials to login for you.

To test our setup:

> ssh -T git@github1
> ssh -T git@github2

Example Git operations:

> git clone git@github1:first_account/sample.git
> git clone git@github2:second_account/sample.git

That's all!


Hello! My name is Jian Jye and I work on Laravel projects as my main job. If my article was helpful to you, a shoutout on Twitter would be awesome! I'm also available for hire if you need any help with Laravel. Contact me.