Set multiple ssh-keys for different GitHub accounts on my Mac

Today when I tried to push update files to my GitHub repository it fails. I guess the reason of that may be that the GitHub account which I tried to push to is different from the GitHub account I was used to use on my Mac. But the new account will be used for two courses this quarter so I have to solve this problem. After some unsuccessful tries, I find out a good tutorial and figure it out finally. For convenience, I will take a note for it in case facing similar situation in the future.

1. Navigate to /.ssh and type ssh-keygen -t rsa -b 4096 -C "new_github@mail.com" to create a new ssh-key

ssh-keygen -t rsa -b 4096 -C "new_github@mail.com"

2. Name the new ssh key, for example, work_rsa, and copy the content from work_rsa.pub

you can use:
pbcopy < ~/.ssh/work_rsa.pub

3. Open your GitHub page, click setting from upper-right corner and click SSH and GPG keys.

4. Click New SSH key or Add SSH key.

5. Pick a name for title and Paste your key into the "Key" field.

6. Open ~/.ssh/config, if not exist then create one.

add the content below to config file.

# Personal GitHub account
Host github.com
 HostName github.com
 User git
 AddKeysToAgent yes
 UseKeychain yes
 IdentityFile ~/.ssh/id_rsa
# Work GitHub account
Host github.com-work
 HostName github.com
 User git
 AddKeysToAgent yes
 UseKeychain yes
 IdentityFile ~/.ssh/work_rsa

7. Clone the work project repo (with a slightly different address)

Use

git clone git@github.com-work:[my work GitHub group]/[my project].git

rather than

git clone git@github.com:[my work GitHub group]/[my project].git

8. Now you can change and push files to your another GitHub account

Leave a Reply