git 配置多端多个账号(码云、github、gitlab)

首先要确认已经安装 Git,可以通过执行 git --version 命令来查看当前安装的版本。

想为同一个电脑配置多个 Git 账户,需要完成以下整体流程:

  1. 清空默认的全局 user.nameuser.email 配置项;
  2. 为不同的 Git 账户生成不同的 SSH 密钥;
  3. 将以上的 SSH 密钥分别添加到 SSH-Agent 信任列表;
  4. 将以上的公钥添加到相应的 Git 账户中;
  5. config 文件中配置多个 SSH 密钥;
  6. 进行测试。

1、清空默认的全局 user.name 和 user.email

bash 复制代码
git config --global --unset user.name
git config --global --unset user.email

可以通过运行 git config --global --list 命令来查看 Git 的全局配置情况。

2、配置多个 Git 账户的用户名和邮箱:

  1. 单个配置
bash 复制代码
git config --global user.name "yourusername"
git config --global user.email "youremail@email.com"
  1. 多个配置

注意: 这里git config命令没有带---global,表示这是一个局部的设置,即该用户只在当前项目中使用,而不是全局的。

bash 复制代码
git config user.name "1"
git config user.email "1@hotmail.com"
  1. 删除配置
bash 复制代码
git config --unset user.name
git config --unset user.email

3、生成多个 SSH 密钥

管理员打开控制台

  1. 生成 gitte 仓库的 SSH

指定文件路径,方便后面操作:~/.ssh/id_rsa.gitee,id_rsa.github是秘钥的别名。

bash 复制代码
ssh-keygen -t rsa -f ~/.ssh/id_rsa.gitee -C "xxxxx@qq.com"
  1. 生成 github 仓库的 SSH
bash 复制代码
ssh-keygen -t rsa -f ~/.ssh/id_rsa.github -C "xxxxx@qq.com"

4、将 ssh-key 分别添加到 ssh-agent 信任列表

js 复制代码
ssh-agent bash
ssh-add ~/.ssh/id_rsa.gitee
ssh-add ~/.ssh/id_rsa.github

如果看到 Identitiy added: ~/.ssh/id_ras_github,就表示添加成功了。

5、将公钥添加到相应的 Git 账户中

使用以下命令将公钥复制到粘贴板中,然后粘贴到 Git 账户的 SSH 密钥中。也可以直接打开文件进行复制,文件名带有 .pub 后缀。

bash 复制代码
pbcopy < ~/.ssh/id_rsa.gitee

6、在 config 文件 (在 .ssh 目录下 ) 中配置多个 SSH 密钥

ini 复制代码
#Default gitHub user Self
Host github
    HostName github.com
    User git #默认就是git,可以不写
    IdentityFile ~/.ssh/id_rsa.github
	
# gitee的配置
host gitee 
	Hostname gitee.com #要连接的服务器
	#密钥文件的地址,注意是私钥
	IdentityFile ~/.ssh/id_rsa.gitee

#Add gitLab user 
Host myGit
    HostName git.xxxxx.cn
    IdentityFile ~/.ssh/id_rsa.xxxx

7、进行测试

bash 复制代码
ssh -T git@gitee.com

git clone git@{配置的 Host}:xxx/xxxx.git
git clone git@myGit:xxx/xxxx.git
相关推荐
Albert_Lsk1 小时前
【2025/07/11】GitHub 今日热门项目
人工智能·开源·github·开源协议
心.c3 小时前
后台管理系统-权限管理
javascript·react.js·github
一点一木3 小时前
🚀 2025 年 06 月 GitHub 十大热门项目排行榜 🔥
前端·人工智能·github
寻月隐君4 小时前
Rust 错误处理终极指南:从 panic! 到 Result 的优雅之道
后端·rust·github
b1ng4 小时前
新人程序员 Git 一站式指南
git·github
叶怀生5 小时前
Github创建仓库并通过VS Code推送项目
github
程序员的世界你不懂5 小时前
IDE 关联 Git 操作
ide·git
weixin_428498497 小时前
Git Submodule 介绍和使用指南
git
ai小鬼头16 小时前
AIStarter新版重磅来袭!永久订阅限时福利抢先看
人工智能·开源·github
如何原谅奋力过但无声16 小时前
上传GitHub步骤(自用版)
github