Git多帐号配置

概述

在公司, 我们可能除了有公司的gitlab帐号,还有github、gitee等帐号。如何在一台机子上同时操作几个git帐号呢?以下以 macOS 为例说明

实战

取消全局设定

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

生成github第一个帐号 SSH Key

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
ssh-keygen -t rsa -C "idea360@foxmail.com"

Generating public/private rsa key pair.
Enter file in which to save the key (/Users/cuishiying/.ssh/id_rsa): id_rsa_idea360
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in id_rsa_idea360.
Your public key has been saved in id_rsa_idea360.pub.
The key fingerprint is:
SHA256:w6Kbf2JXBcRul4t48utPGHFBlX446qh8JUCs4NXS2tI idea360@foxmail.com
The key's randomart image is:
+---[RSA 3072]----+
| + o..o... |
| . o = o .. |
| . o B ....o . |
| . +.E oo+ + .|
| ..S+.+ o o |
| . .o.=o+ |
| . =.=. |
| oo.o +.. |
| oo.+o+oo. |
+----[SHA256]-----+

生成第二个帐号同理。

在github上添加key

1
cat id_rsa_idea360.pub

登录 GitHub 账号,点击 Settings->SSH and GPG keys>New SSH Key 进行添加

本地 SSH Agent中添加Key

1
ssh-add -K ~/.ssh/id_rsa_idea360

修改 SSH config 文件

config 文件不是默认生产的,有些人可能会没有,所以可以先创建一个。先进入到 .ssh 文件中cd ~/.ssh,然后执行 touch config进行创建。

1
2
3
4
5
# idea360
Host idea360.github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_idea360

OK,现在让我们测试一下配置是否成功:

1
2
ssh -T git@idea360.github.com
ssh -T git@cuishiying163.github.com

如果输出以下内容:

1
Hi qidian360! You've successfully authenticated, but GitHub does not provide shell access.

恭喜你,已经配置成功了!慢着慢着,刚才把全局设置给取消了,现在是不是要单独设置回来,没错,取消了全局设置的用户和邮箱后,我们要为每一个项目进行单独设置。

最后一步

由于我们设置了 Host,这就相当于是 HostName 的别名。比如现在对个人 GitHub 上的 repo 进行 clone 的时候,要改成 git clone git@idea360.github.com:xxx/xxx.git。即替换github.com域名为我们配置的Host

1
git clone git@idea360.github.com:qidian360/spring-cloud-learning.git

如果是已经克隆到本地的项目,则可以在项目中修改:

1
2
$ git remote rm origin
$ git remote add origin git@idea360.github.com:qidian360/blog.git

可以执行 git remote -v 查看是否修改成功。

然后在每个项目中,执行:

1
2
git config user.email "idea360@foxmail.com"
git config user.name "qidian360"

对公司和个人项目单独设置用户名和邮箱。
可以查看一下:

1
2
git config user.name
git config user.email

push 的话还是照常使用:git push origin master

最后

本文到此结束,感谢阅读。如果您觉得不错,请关注公众号【当我遇上你】,您的支持是我写作的最大动力。