Mac多个Git账户配置

生成 SSH key

1
ssh-keygen -t rsa -C "your_email@example.com"

-t: The type of the key to generate
密钥的类型
-C: comment to identify the key
用于识别这个密钥的注释,所以这个邮箱你可以输入任何内容

将 ssh key 添加到 GitHub 中

avatar
图中选中两个为公钥,将两个公钥内容分别添加到两个 github 账户中

在 config 文件配置多个 ssh-key

在~/.ssh 目录下新建 config 文件

1
2
3
4
5
6
7
8
9
10
11
Host Ning
HostName github.com
PreferredAuthentications publickey
User git
IdentityFile ~/.ssh/id_rsa

Host Near
HostName github.com
PreferredAuthentications publickey
User git
IdentityFile ~/.ssh/id_rsa_near

测试链接

1
2
ssh -T Ning
ssh -T Near

直接连接 host 即可,克隆 git 代码的时候需要用 ssh 的链接克隆。
比如复制的地址为:git@github.com:yangjiagongzi/yangjiagongzi.github.io.git:前面的字符串用 host 代替,用 Near 账户的话命令为git clone Near:yangjiagongzi/yangjiagongzi.github.io.git
我们可以看到 Host 代替了git@github.com这个字符串,而@前面的字符串为 User, 后面的字符串为 HoseName, 在我们的配置中也需要保持 User 和 HoseName 的正确

修改已下载项目的推送地址

打开项目中.git文件夹,可以看到有一个 config 文件,将文件中的url字段按照克隆的方式修改后推送代码将自动改为 ssh。

1
2
3
4
5
6
7
8
9
10
11
12
13
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
precomposeunicode = true
[remote "origin"]
url = Near:yangjiagongzi/blog.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master