
日常使用 git 作为仓库使用时,会遇到以下情况:
- 有两个 github 账号(至少两个),一台电脑同时连接这两个账号进行维护
- 私人 github 账号,公司 gitlab 账号
一、清除 git 的全局设置(针对已安装 git)
新安装 git 跳过。
若之前对 git 设置过全局的 user.name 和 user.email。 类似(用git config –global –list 进行查看你是否设置)
| 12
 
 | $ git config --global user.name "你的名字"$ git config --global user.email  "你的邮箱"
 
 | 
必须删除该设置
| 12
 
 | $ git config --global --unset user.name "你的名字"$ git config --global --unset user.email "你的邮箱"
 
 | 
按项目设置
| 12
 
 | $ git config --local user.name "你的名字"$ git config --local user.email  "你的邮箱"
 
 | 
二、生成新的 SSH keys
(1)#GitHub的钥匙
| 12
 
 | ssh-keygen -t rsa -C "xxx@xx.com"Enter file in which to save the key (/Users/kingboy/.ssh/id_rsa): /Users/kingboy/.ssh/github_id_rsa
 
 | 
(2)#gitlab
| 12
 
 | ssh-keygen -t rsa -C "xxx@xx.com"Enter file in which to save the key (/Users/kingboy/.ssh/id_rsa): /Users/kingboy/.ssh/gitlab_id_rsa
 
 | 
注意:输入的是钥匙的位置和名称。github和gitlab是不同的。
(3)完成后会在~/.ssh/目录下生成以下文件:
| 12
 3
 4
 
 | github_id_rsagithub_id_rsa.pub
 gitlab_id_rsa
 gitlab_id_rsa.pub
 
 | 
三、添加识别 SSH keys 新的私钥
默认只读取 id_rsa,为了让 SSH 识别新的私钥,需要将新的私钥加入到 SSH agent 中
| 12
 3
 
 | $ ssh-agent bash$ ssh-add ~/.ssh/github_id_rsa
 $ ssh-add ~/.ssh/gitlab_id_rsa
 
 | 
四、多账号必须配置 config 文件
若无 config 文件,则需创建 config 文件
config 里需要填的内容
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 
 | #Default gitHub user SelfHost github.com
 HostName github.com
 User github
 IdentityFile ~/.ssh/github_id_rsa
 
 #Add gitLab user
 Host git@git.gitlab.com
 HostName git@git.gitlab.com
 User gitlab
 IdentityFile ~/.ssh/gitlab_id_rsa
 
 | 
五、在github和gitlab网站添加ssh
六、测试是否连接成功
| 12
 3
 4
 5
 
 | $ ssh -T git@github.com
 
 
 $ ssh -T git@gitlab.com
 
 | 
七、修改commit中的author
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 
 | #!/bin/bash git filter-branch  --force --env-filter '
 #如果Git用户名等于老的Git用户名 snaildev
 if [ "$GIT_COMMITTER_NAME" = "snaildev" ] || [ "$GIT_AUTHOR_EMAIL" = "snaildev@outlook.com" ];
 then
 #替换用户名为新的用户名,替换邮箱为正确的邮箱
 GIT_AUTHOR_NAME="snaildev";
 GIT_AUTHOR_EMAIL="snailtem@gmail.com";
 
 #替换提交的用户名为新的用户名,替换提交的邮箱为正确的邮箱
 GIT_COMMITTER_NAME="snaildev";
 GIT_COMMITTER_EMAIL="snailtem@gmail.com";
 fi
 ' --tag-name-filter cat -- --branches --tags
 
 git push -f
 
 
 git pull --allow-unrelated-histories
 
 |