stackjlei stackjlei - 1 month ago 9
Git Question

How to have 2 git users on one computer?

I want to practice using GitHub doing pull requests and learning about how to see git difference between different users. How do I set up another user account on my terminal in macOS to do this? How do I switch between users?

tom tom
Answer

There are three aspects to acting as a second user.

1. GitHub Account

To use the GitHub web interface as another user (e.g. fork a repository, submit a pull request, post comments) you need to sign in to another account.*

Tip: Switching between accounts is a pain because you have to sign out and sign in each time. You can sign in to two accounts at the same time using a private browsing window, a different browser, or a different browser profile.

2. SSH Authentication

A GitHub repository can be accessed over HTTPS or SSH. Both require authentication, which GitHub uses to implement permission levels. I'll describe how to clone a repository with SSH configured to authenticate as a second user.

Generate a new SSH key using ssh-keygen -f KEYFILE where KEYFILE is the path to the new key (e.g. ~/.ssh/bob_rsa).

Add the SSH key to the GitHub account of the second user.

SSH needs to be configured to use ~/.ssh/bob_rsa, but only for repositories cloned as the second user. Different configurations can be specified based on the host name, but for GitHub repositories the host name is always github.com. To specify configurations for only some of the cloned repositories, add a host alias by appending the following to ~/.ssh/config (credit):

# alias for github.com with a custom SSH key
Host bob.github.com
    HostName github.com
    IdentityFile ~/.ssh/bob_rsa

Now you can clone a GitHub repository as the second user using the host name bob.github.com:

git clone git@bob.github.com/USER/PROJECT.git

If you clone a repository owned by your first user in this way, you should not be able to push commits to it until you add your second user as a collaborator.

3. Git Author Metadata

Git stores the author's name and email address with each commit. GitHub uses this information to display user avatars in the commit history for example. It is trivial to spoof this information (1, 2).

The author's name and email address are usually stored in the global configuration file (~/.gitconfig). You can override them on a per-repository basis by running the following in the repository's directory:

git config --local user.name "NAME"
git config --local user.email "EMAIL"

Replace NAME and EMAIL with the full name and email address of the second user. The --local flag modifies the per-repository configuration file (.git/config in the repository's root directory).

Now you have a clone where you are effectively the second user. Use another (normal) clone to work as the first user.


*Fine print: GitHub's Terms of Service only allow one free account per person.