How to set up multiple git accounts on one machine
Preface
Because of the hot summer weather, I choose not to take the company’s MacBook Pro 2019 home. Moreover, this model is very heavy and has an unsatisfactory keyboard. After setting up my own development environment on my Mac, all I need to bring home every day is my YubiKey.
Setting up multiple git accounts
Generate a new SSH key for the office account.
Remember to paste the public key in the GitHub settings.
ssh-keygen -t ed25519 -C "your_email@example.com"
Adding your SSH key to the ssh-agent
Start the ssh-agent in the background.
eval "$(ssh-agent -s)"
Editing the ~/.ssh/config
Host personal-account
HostName github.com
AddKeysToAgent yes
IdentityFile ~/.ssh/id_ed25519_personal.pub
Host office-account
HostName github.com
AddKeysToAgent yes
IdentityFile ~/.ssh/id_ed25519_office
Adding key to the ssh-agent
ssh-add ~/.ssh/id_ed25519_personal
ssh-add ~/.ssh/id_ed25519_office
Setting up the repository
Cloning GitHub repositories using different accounts
git clone git:personal-account:{owner-username}/{the-repository-name}.git
git clone git:office-account:{owner-username}/{the-repository-name}.git
Setting up individual usernames and emails for repositories
After cloning the repository, it is important to set up the correct GitHub username and email for each repository on the system.
This ensures that commits and pushes are associated with the appropriate user.
git config user.email "your-personal-email@gmail.com"
git config user.name "your-personal-github-username"
git config user.email "your-office-email@gmail.com"
git config user.name "your-office-github-username"
Modifying the URL for the Git origin
To ensure successful pushing to the remote branch, we need to modify the URL for the git origin.
git remote set-url origin git@personal:{owner-username}/{the-repository-name}.git
git remote set-url origin git@office:{owner-username}/{the-repository-name}.git
To verify, run the command git remote -v
.
Setting up the GPG keys(optional)
If you have previously set up GPG on your new git account, remember to import it onto the new machine.
gpg import <key-id>
To enable GPG key signing for the repository.
gpg --list-secret-keys --keyid-format LONG
git config user.signingkey XXXXXXXXXXXXX
git config commit.gpgsign true
Finally
From now on, you can push or pull as usual.