Switch between user identities in one Git on one computer

GitGithub

Git Problem Overview


I have ONE repository on GitHub, let's call it Repo-1.

I want to first access that repository as a default Git user.

Let's call that user User-1.

I created SSH keypair, everything fine, works nice.


I made ANOTHER repository on GitHub, let's call it Repo-2.

I didn't make any changes in local Git, on my laptop. No configurational changes, nothing.

Now - I want to clone from Repo-1 as the User-2 (but from the same laptop).

First of all: is this at all possible to do?

Can local Git on one single laptop switch between "user accounts" and present itself as User-2? And then, from THAT identity, clone from Repo-1, make some change, and then push to Repo-1?

If possible, how do I do that?

Git Solutions


Solution 1 - Git

You have your global .gitconfig where you already configured your SSH Keys/User Information. The global .gitconfig is overridden by a local gitconfig - the file "config" in your .git folder (if it does not exist you might have to create it).

For example you can copy the .gitconfig file into the .git folder (and rename it to "config") and just change the lines you want to change (probably github.user and github.token) or you create a new file with just the two lines in it.

If you prefer the command line "git config" you can avoid all the file moving stuff by omitting the "--global" option.

Solution 2 - Git

You need to determine if you actually have two ssh keypairs, or just two emails you want to use. An ssh keypair is linked to accounts as described here.

The ssh keypair (specifically the private key), basically gives your git client permission to connect to github, and thus permission to push. This is separate from the user identity, which is just the email in your commit messages.

If you have two ssh keypairs, each linked to one account, follow these instructions to create a ~/.ssh/config file. The key part is to use a different ssh psuedo-host for each account:

# Default GitHub user (joe)
Host github.com
  HostName github.com
  User git
  IdentityFile /Users/joe/.ssh/id_rsa

# Client user (client)
Host github-client
  HostName github.com
  User git
  IdentityFile /Users/joe/.ssh/id_rsa_client

You then use two corresponding remotes:

git clone [email protected]:joe/my_repo.git

and

git clone git@github-client:client/his_repo.git

If you just want to use two emails, you can just give each clone a separate .git/config with the desired [user] settings.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartinView Question on Stackoverflow
Solution 1 - GitMoeView Answer on Stackoverflow
Solution 2 - GitMatthew FlaschenView Answer on Stackoverflow