git多账号通过ssh提交

假设我有两个 github 账号,victor(for personal) 和 superman(for work)。如果我想在同一台电脑上使用这两个账号进行 git push/pull。该如何配置?

推荐解决方案

  1. 由于github 现在已经不支持 http 方式 push。所以首先需要生成 ssh key,并将 ssh key 加入 github 账号.

  2. 按照如下方式设置 ssh 配置文件~/.ssh/config

1
2
3
4
5
6
7
8
9
10
11
12
13
# work github account: superman
Host github.superman
HostName github.com
User git
IdentityFile ~/.ssh/superman_private_key
IdentitiesOnly yes

# personal github account: victor
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/victor_private_key
IdentitiesOnly yes
  1. 向 ssh agent 中加入私钥
1
2
$ ssh-add ~/.ssh/victor_private_key
$ ssh-add ~/.ssh/superman_private_key
  1. 测试连接
1
2
$ ssh -T git@github.com
$ ssh -T git@github.superman
  1. 克隆项目
1
2
3
4
5
6
7
8
9
10
# 工作项目克隆
$ git clone git@github.superman:xxx/project1.git /path/to/project1
$ cd /path/to/project1
$ git config user.email "superman@example.com"
$ git config user.name "Super Man"
# 个人项目克隆
$ git clone git@github.com:xxx/project2.git /path/to/project2
$ cd /path/to/project2
$ git config user.email "Victor@example.com"
$ git config user.name "Victor"

临时解决方案

通过指定私钥文件来临时支持。

1
GIT_SSH_COMMAND='ssh -i PATH/TO/KEY/FILE -o IdentitiesOnly=yes' git clone git@github.com:OWNER/REPOSITORY

上面的命令也可以封装为脚本git-me.sh:

1
2
3
4
5
#!/usr/bin/env bash

SSH_PRIVATE_KEY=~/.ssh/personal_private_key.pem

GIT_SSH_COMMAND="ssh -i $SSH_PRIVATE_KEY -o IdentitiesOnly=yes" git $@

参考