Git多账号配置指南

224 阅读1分钟

前言

当你需要同时使用公司的GitLab和自己的Gitee项目时,通常会遇到配置单一全局用户名无法满足不同平台需求的问题。

为了解决这个问题,你可以按照以下步骤设置Git以支持多个账户。

步骤

1. 移除用户名配置

git config --global --unset user.name xxx
git config --global --unset user.email xxx@xxx.com

2. 生成SSH秘钥

// gitlab
ssh-keygen -t rsa -f ~/.ssh/id_rsa.gitlab -C "xxx@xxx.com"
// gitee
ssh-keygen -t rsa -f ~/.ssh/id_rsa.gitee -C "yyy@yyy.com"

3. 私钥加入到 SSH agent

ssh-add ~/.ssh/id_rsa.gitlab
ssh-add ~/.ssh/id_rsa.gitee

4. 配置SSH config

配置文件为~/.ssh/config,这里通过vim打开

vim ~/.ssh/config

配置内容

# gitlab
Host 192.168.13.28
    AddKeysToAgent yes
    UseKeychain yes
    HostName 192.168.13.28
    IdentityFile ~/.ssh/id_rsa.gitlab
    
# gitee
Host gitee.com
    AddKeysToAgent yes
    UseKeychain yes
    HostName gitee.com
    IdentityFile ~/.ssh/id_rsa.gitee

5. 配置公钥到gitlab/gitee网站

查看公钥

cat ~/.ssh/id_rsa.gitee.pub

在网站上配置公钥

image-20240812192143862.png