Setting up git to work with multiple accounts

If you have a personal and a separate work account on GitHub, the git and ssh-agent can often get confused depending on your work habits. This article describes the steps you need to take to make them work nicely side-by-side.

Instructions

The solution that worked for me is based on how ssh config works on macOS and Linux systems.

1. In the home directory of your user, create a folder named .ssh if it doesn't already exist.

2. Create a file called config, and if it already exists, edit it.

3. Inside the config file, we can add an alias to the GitHub hosts as follows:

#user1 account
Host github.com-user1
   HostName github.com
   User git
   IdentityFile ~/.ssh/github-user1
   IdentitiesOnly yes

#user2 account
Host github.com-user2
   HostName github.com
   User git
   IdentityFile ~/.ssh/github-user2
   IdentitiesOnly yes

4. Replace user1 and user2 according to your needs. The IdentityFile needs to be a key that you’ve uploaded to GitHub. You can do it afterward, but the names need to match.

If you're running macOS, you can configure ssh-agent to use the keychain and to add keys to the keychain by adding the following two settings: UseKeychain yes and AddKeysToAgent yes.

5. Once you've completed the above steps, it's time to clone the repositories. To do so, copy the ssh URL from the GitHub interface, but don't run it yet.

For example, if I clone repository xyz, I will get from GitHub something like:

[email protected]:example-org/xyz.git

Update it to match your configuration inside ~/.ssh/config so that it looks something like:

[email protected]:example-org/xyz.git

Now you can clone the repo by running:

git clone [email protected]:example-org/xyz.git xyz

The clone command will automatically set the remote for your repo.

If you already have it cloned, you can update your remote URL to take the form above.

git remote set-url origin [email protected]:example-org/xyz.git

6. Lastly, you need to configure the correct name and email for your repository.

To do so, run:

git config --local -e

The command above will open up your default editor, and there you can provide the following snippet:

[user]
        name = user1
        email = [email protected]

Related articles