多账户git配置
多账户git配置
前言
日常工作中企业会有单独的git仓库地址,私人的代码一般都放在gitlab,所以就会面临多账户的问题,通过询问AI,解决方法如下。
解决方法
-
创建多个ssh密钥
-
```
# 为GitHub创建SSH密钥
ssh-keygen -t ed25519 -C "[email protected]" -f ~/.ssh/github_key为GitLab创建SSH密钥
ssh-keygen -t ed25519 -C "[email protected]" -f ~/.ssh/gitlab_key
为公司内部Git服务器创建SSH密钥
ssh-keygen -t ed25519 -C "[email protected]" -f ~/.ssh/company_key
``` -
配置SSH的config文件
-
编辑或者创建
~/.ssh/config文件: -
```
# GitHub账号配置
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/github_key
IdentitiesOnly yesGitLab账号配置
Host gitlab.com
HostName gitlab.com
User git
IdentityFile ~/.ssh/gitlab_key
IdentitiesOnly yes公司内部Git服务器配置
Host git.company.com
HostName git.company.com
User git
IdentityFile ~/.ssh/company_key
IdentitiesOnly yes如果您有多个GitHub账号,可以使用别名
Host github-personal
HostName github.com
User git
IdentityFile ~/.ssh/github_personal_key
IdentitiesOnly yes
``` -
将公钥添加到对应的Git服务
-
# 复制GitHub密钥 cat ~/.ssh/github_key.pub | pbcopy # macOS # 或 cat ~/.ssh/github_key.pub | xclip -selection clipboard # Linux -
验证配置
-
```
# 测试GitHub连接
ssh -T [email protected]测试GitLab连接
ssh -T [email protected]
``` -
基于目录自动配置用户名
-
在全局Git配置中添加条件包含,gitdir之后的目录匹配按照自己实际的去修改
- ```
# 编辑全局Git配置
vim ~/.gitconfig
# 添加如下内容
[includeIf "gitdir:~/work/"]
path = ~/.gitconfig-work
[includeIf "gitdir:~/personal/"]
path = ~/.gitconfig-personal
``` - ```
-
创建对应的配置文件
- ```
# 工作项目配置 (~/.gitconfig-work)
[user]
name = 工作用户名
email = [email protected]
# 个人项目配置 (~/.gitconfig-personal)
[user]
name = 个人用户名
email = [email protected]
``` - ```
结语
该方案可以在指定的目录下自动切换git用户名,根据请求网址不同使用不同的ssh密钥连接。