同个电脑里不同 GitHub 账号对不同仓库进行提交

步骤一:为每个 GitHub 账号生成独立的 SSH 密钥

1
2
3
4
5
# 为jack生成密钥
ssh-keygen -t ed25519 -C "jack@example.com" -f ~/.ssh/id_ed25519_jack

# 为mike生成密钥
ssh-keygen -t ed25519 -C "mike@company.com" -f ~/.ssh/id_ed25519_mike

密钥文件建议命名清晰,如 id_ed25519_jackid_ed25519_mike

步骤二:配置 SSH config 文件(~/.ssh/config

1
2
3
4
5
6
7
8
9
10
11
# jack GitHub account
Host github.com-jack
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_jack

# mike GitHub account
Host github.com-mike
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_mike

这样可以使用 github.com-jackgithub.com-mike 作为远程主机别名。

步骤三:克隆仓库时使用对应的 Host 别名

  • jack 项目

    1
    git clone git@github.com-jack:yourname/jack-repo.git

注意:把原始 URL 中的 github.com 替换为 github.com-jackgithub.com-mike

步骤四:在每个仓库内单独配置 Git 用户信息

Git 的 user.nameuser.email 可以在仓库级别(local)设置,覆盖全局配置:

1
2
3
4
# 进入jack仓库
cd ~/projects/jack-repo
git config user.name "Your Personal Name"
git config user.email "jack@example.com"

✅ 这样提交日志中的作者信息会与对应账号匹配,GitHub 也会正确识别贡献。


(可选)检查配置是否生效

1
2
3
4
5
6
7
# 查看当前仓库的 Git 配置
git config --local user.name
git config --local user.email

# 测试 SSH 连接(可选)
ssh -T git@github.com-jack
ssh -T git@github.com-mike

如果提示 “You’ve successfully authenticated”,说明 SSH 配置正确。