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.
Add the following lines into your
Host github1 User git Hostname github.com IdentityFile ~/.ssh/id_rsa_first Host github2 User git Hostname github.com 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
github2 setup in the config file earlier? This is the key.
For all your future operations, replace
github.com with either
github2 and SSH will use the correct credentials to login for you.
To test our setup:
ssh -T [email protected] ssh -T [email protected]
Example Git operations:
git clone [email protected]:first_account/sample.git git clone [email protected]:second_account/sample.git