Multiple Git Accounts on Mac
Clear Existing Config
Check current Git configuration:
git config --listClear username and email:
git config --global --unset user.namegit config --global --unset user.emailGenerate SSH Keys
Use ssh-keygen to generate SSH keys with manually specified IDs:
ssh-keygen -t rsa -f ~/.ssh/id_rsa_xx1@gmail.com -C "xx1@gmail.com"Successful generation outputs:
Generating public/private rsa key pair.Enter file in which to save the key (/Users/james/.ssh/id_rsa):Enter passphrase (empty for no passphrase):Enter same passphrase again:Your identification has been saved in /Users/james/.ssh/id_rsa.Your public key has been saved in /Users/james/.ssh/id_rsa.pub.The key fingerprint is:SHA256:rwtxjGTJPoV9Mg8lFSf8D4X6jFexWVXKOMRaVyo+RO8 xx1@gmail.comThe key's randomart image is:+---[RSA 3072]----+| .o=o+. .*|| . + o.=+++o.|| * * .==o== || + + *ooo++ || = S .+o+E || + .. +.. || . .. || . . || o. |+----[SHA256]-----+Continue generating SSH keys for your other Git accounts:
ssh-keygen -t rsa -f ~/.ssh/id_rsa_xx2@gmail.com -C "xx2@gmail.com"Trust SSH Keys
Add generated SSH keys to the ssh-agent trust list using ssh-add:
ssh-add ~/.ssh/id_rsa_xx1@gmail.comssh-add ~/.ssh/id_rsa_xx2@gmail.comIf you encounter Could not open a connection to your authentication agent., run:
ssh-agent bashThen re-execute the ssh-add commands.
Configure Public Keys
Copy the corresponding public keys and add them to the respective Git platform (GitHub / GitLab):
pbcopy < ~/.ssh/id_rsa_xx1@gmail.com.pubpbcopy < ~/.ssh/id_rsa_xx2@gmail.com.pubFor detailed steps, refer to Adding a new SSH key to your GitHub account.
Configure SSH Config
Navigate to the SSH directory:
open ~/.ssh/Edit the config file (create if it doesn’t exist) following these rules:
| Key | Value | Description |
|---|---|---|
| Host | hostname | Custom name |
| Hostname | host address | Git public address, e.g., github.com / gitee.com |
| IdentityFile | identity file | RSA file path |
| User | user | Custom, typically your email |
Example config:
Host github1.comHostname github.comIdentityFile ~/.ssh/id_rsa_xx1@gmail.comUser xx1@gmail.com
Host github2.comHostname github.comIdentityFile ~/.ssh/id_rsa_xx2@gmail.comUser xx2@gmail.comTest Connection
Test whether Git accounts connect successfully. The part after git@ is the Host from your config file:
ssh -T git@github1.comssh -T git@github2.comSuccessful connection outputs:
Hi xxx! You've successfully authenticated, but GitHub does not provide shell access.