同一客户端使用多个 git 账号

有时候我们希望自己的 github 使用一个私钥,公司的 git 账号使用另一个私钥。这样就需要在客户端上配置支持多个 git 账号。

清除 Git 的全局设置

git config --global --unset user.name
git config --global --unset user.email

生成新的 SSH keys

使用 ssh-keygen 生成新的秘钥对。注意这个时候需要输入文件名,使用默认的名字会覆盖已有的。比如这里使用名字 id_rsa_new

执行 ssh-agent 让 ssh 识别新的私钥

SSH 默认只读 id_rsa,为了让 SSH 识别新的私钥,需要将其添加到 SSH agent 中

ssh-add ~/.ssh/id_rsa_new

// 如果出现了 Could not open a connection to your authentication agent 就使用以下命令
ssh-agent bash
ssh-add ~/.ssh/id_rsa_new

配置 ~/.ssh/config 文件

Host git@github.com
        HostName github.com
        User git
        IdentityFile ~/.ssh/id_rsa

Host git@gitee.com
        HostName <https://gitee.com>
        User git
        IdentityFile ~/.ssh/id_rsa_new

参考

同一客户端下使用多个 Git 账号