如何管理两个Git账户
背景
在开发过程中,我们有时需要同时使用 多个 Git 账户(如个人 GitHub 账户和公司 GitLab 账户)。但由于 Git 默认使用全局配置,可能会导致提交信息混乱、权限冲突等问题。本文将介绍如何在同一台机器上 安全、高效地管理多个 Git 账户。
流程
1.生成不同的 SSH 密钥对
- 生成第一个账户的密钥(如个人 GitHub)
ssh-keygen -t ed25519 -C "personal@example.com" -f ~/.ssh/id_ed25519_personal
- 生成第二个账户的密钥(如公司 GitLab)
ssh-keygen -t ed25519 -C "work@company.com" -f ~/.ssh/id_ed25519_work
2. 将 SSH 公钥添加到对应的 Git 平台
- Github:
Settings → SSH and GPG Keys → New SSH Key
- GitLab:
Preferences → SSH Keys
复制公钥内容(如~/.ssh/id_ed25519_personal.pub
)并粘贴到对应平台。
3. 配置 SSH 区分账户
编辑 ~/.ssh/config
文件,为每个账户指定不同的主机别名和密钥:
nano ~/.ssh/config
添加如下配置:
# 个人 GitHub 账户
Host github.com-personal # 自定义别名HostName github.comUser gitIdentityFile ~/.ssh/id_ed25519_personal# 公司 GitLab 账户
Host gitlab.com-work # 自定义别名HostName gitlab.comUser gitIdentityFile ~/.ssh/id_ed25519_work
保存后退出
4. 测试连接
ssh -T git@github.com-personal
ssh -T git@gitlab.com-work
5. 修改 Git 仓库的 Remote URL
⭐️⭐️⭐️将仓库的 remote URL 改为对应的 SSH 别名:
# 个人仓库
git remote set-url origin git@github.com-personal:username/repo.git# 公司仓库
git remote set-url origin git@gitlab.com-work:company/repo.git