Qingquan-Li / blog

My Blog
https://Qingquan-Li.github.io/blog/
134 stars 16 forks source link

Work With Two Git/GitHub Accounts On One Computer #221

Open Qingquan-Li opened 2 years ago

Qingquan-Li commented 2 years ago

1. Create SSH Key

Generate a unique SSH key for second GitHub account.

$ ssh-keygen -t ed25519 -C "account2@email.com"
Generating public/private ed25519 key pair.
Enter file in which to save the key (/Users/username/.ssh/id_ed25519): id_ed25519_account2
...

2. Add the New SSH key to the Second GitHub Account

Copy the SSH public key (~/.ssh/id_ed25519_account2.pub) to the second GitHub account: https://github.com/settings/keys

3. Add the SSH Key to the Agent

$ ssh-add ~/.ssh/id_ed25519 # default SSH key
Identity added: /Users/username/.ssh/id_ed25519 (account1@email.com)
$ ssh-add ~/.ssh/id_ed25519_account2
Identity added: /Users/username/.ssh/id_ed25519_account2 (account2@email.com)

4. Configure the config File

$ vim ~/.ssh/config
#Default GitHub Account
Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519

Host github.com-account2
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519_account2

5. Change Remote Repository URL

Use git@github.com-account2 instead of git@github.com

$ git remote set-url origin git@github.com-account2:your-github-username/repository-name.git

6. Change (Local) Git Username and Email

If you have set the global config,

$ git config --global user.name "your-name-of-account1"
$ git config --global user.email account1@email.com

then you can change the user.name and user.email locally for the current repository.

$ git config user.name "your-name-of-account2"
$ git config user.email "account2@email.com"
PhilipMello commented 3 months ago

Simple script to work with 2 Git/GitHub in one terminal. The the tool allows to: create ssh keys, change between 2 accounts, verify the current account and test connection to github. https://github.com/PhilipMello/git-switch