How to switch between two git accounts on same device, in the Terminal (WSL2)?

Viewed 1784

I have created two separate GitHub accounts.

I have also generated two separate SSH keys for them too, using the same device.

When I typed git config user.name in the terminal, the output shows USERNAME2.

I want to work in account 1 right now, so I typed git config --global user.name "USERNAME1 and did the same for the email.

But I think that it hasn't truly switched accounts and just renamed my username or something? The reason I think that is because when I'm trying to create a new repo in account, for ALL git commands, I keep getting a fatal: not a git repository (or any of the parent directories): .git error, which I never got before now, when I had a single account running.

My SSH keys are in two different folders (for account1, it's in .ssh in the home dir, and for account2, it's in .newssh folder in home dir).

What do I do?

2 Answers

I want to work in account 1 right now, so I typed git config --global user.name "USERNAME1"

That has nothing to do with remote Git server authentication.
It only sets local commit authorship.

To use different accounts, you need different remote URLs, each URL set to use the proper private ssh key for remote authentication.

This is done with ~/.ssh/config, as shown here.

Host github2
HostName github.com
User git
IdentityFile /home/me/.newssh/key2

And it supposes:

  • you have git init myProjectFolder, in order to work within ProjectFolder

  • you have set the correct remote URL in the Projectfolder

      git remote add origin github2:<me>/myProject
    

Step-by-step, assuming an active shell session in WSL2 (do change the names by something more meaningful to you)

  1. generate SSH keys, one per account
cd ~/.ssh
ssh-keygen -t rsa -P "" -f account1
ssh-keygen -t rsa -P "" -f account2
  1. Register account1.pub and accuont2.pub to their respective GitHub account: see "Adding a new SSH key to your GitHub account"

  2. Setup ~/.ssh/config with:

Host account1
  HostName github.com
  User git
  IdentityFile ~/.ssh/account1
Host account2
  HostName github.com
  User git
  IdentityFile ~/.ssh/account2
  1. Clone your repositories using the right URL (and with it, the right account)
cd
git clone account1:<NameAccount1>/<Repo1>
git clone account1:<NameAccount2>/<Repo2>

(<...> are placeholder values, meant to be replaced: do not keep < and >)

  1. In each repository, set the right commit authroship
cd ~/<repo1>
git config user.name <NameAccount1>
git config user.email <NameAccount1@email.com> # the one registered with GitHub

cd ~/<repo2>
git config user.name <NameAccount2>
git config user.email <NameAccount2@email.com> # the one registered with GitHub

After those steps, each commit will be done with the right GitHub account, and push to the right GitHub repository.

You can use only one ssh key, just add the pub key to both github accounts.

Related