Using Multiple GitHub Accounts on the Same Machine

·

2 min read

This is a small overview of how you can use Git with multiple accounts, focused on Windows but should work for other operating systems as well.

Pre-requisites:

  • Git is installed, alongside Git Bash if on Windows

  • You are wanting to use multiple GitHub accounts (eg work, personal) in the same environment

TLDR:

  • generate your public/private keys and add the public key to GitHub

  • configure Git for multiple accounts

  • test your credentials

  • celebrate

Generate your public / private keys

Skip if you already have done this

For each account

Note: the ~/.ssh directory is typical, C:\Users\<user>\.ssh on Windows, but will resolve using GitBash anyway).

If you have existing keys in ~/.ssh, it may make sense to back them up somewhere

Run the following, replacing <git-username> with your username.

export username=yourgitusername  # replace this with your GitHub username
mkdir -p ~/.ssh/$username 

# generate the key, the doubling of the username variable is intentional
ssh-keygen -t ed25519 -C "your-email@example.com" -f ~/.ssh/$username/$username

# finally, cat the output of the .pub file, you'll need this in the next step
cat -f ~/.ssh/$username/$username.pub

Login to GitHub for your first account and go to the top right, click Settings:

Then SSH and GPG keys and click New SSH key.

Enter a name, keep it as "Authentication key" and then paste the public key contents that you output via "cat". Click "Add SSH Key".

Create SSH Config File

Now, we need to create or update an ssh config file that maps each of our GitHub usernames with the associated key files.

Create the file if it doesn't exist:

touch ~/.ssh/config

Add the following to it, updating the placeholder to your GitHub username:

Host <username>
    HostName github.com
    AddKeysToAgent yes
    User git
    IdentityFile ~/.ssh/<username>/<username>

Repeat for each GitHub username.

Test Your Credentials

Now, run the following to ensure your credentials are correct:

ssh -T git@<username>
#the following will be returned
Hi <username>! You've successfully authenticated, but GitHub does not provide shell access.

Then you should be able to clone your repositories via SSH:

# notice there is no github.com here, we load that from the config file above instead using the relevant key.
git clone git@<username>/my-sweet-repo.git

Finally:

export username=

Let me know in the comments if this helps or if you are running into any issues.

Thanks,

Michael.