Git使用心得——配置本地用户名
问题背景
当你在两台电脑上使用同一个GitHub账号但不同的SSH密钥时,可能会遇到以下问题:
核心原理
1. SSH密钥与邮箱的分工
| 组件 |
作用域 |
功能描述 |
| SSH密钥 |
仓库操作权限 |
代码推送/拉取的鉴权 |
| Git邮箱配置 |
提交记录归属 |
决定提交者身份显示 |
2. GitHub账号关联规则
- 邮箱匹配:提交记录中的邮箱必须与GitHub账号的已验证邮箱一致
- 密钥绑定:SSH密钥需添加到目标账号的
Settings → SSH and GPG keys
完整配置方案
步骤1:统一邮箱配置
在两台电脑上配置完全相同的邮箱(必须与GitHub账号已验证邮箱一致)
1 2 3 4 5 6
| git config --global user.email "your_verified_email@example.com" git config --global user.name "YourGitHubUsername"
git config --global --get user.email
|
步骤2:独立SSH密钥配置
为每台电脑生成独立的SSH密钥:
1 2 3 4 5
| ssh-keygen -t ed25519 -C "your_verified_email@example.com" -f ~/.ssh/github_pcA
ssh-keygen -t ed25519 -C "your_verified_email@example.com" -f ~/.ssh/github_pcB
|
步骤3:配置SSH代理
编辑 ~/.ssh/config 文件:
1 2 3 4 5 6 7 8 9 10 11 12 13
| Host github.com-pcA HostName github.com User git IdentityFile ~/.ssh/github_pcA IdentitiesOnly yes
Host github.com-pcB HostName github.com User git IdentityFile ~/.ssh/github_pcB IdentitiesOnly yes
|
步骤4:修改仓库远程地址
1 2 3 4
| git remote set-url origin git@github.com-pcA:username/repo.git
git remote set-url origin git@github.com-pcB:username/repo.git
|
验证配置
1. SSH连接测试
1 2 3 4 5 6 7
| ssh -T git@github.com-pcA
ssh -T git@github.com-pcB
|
2. 提交记录验证
1 2 3 4 5 6
| echo "test" >> test.txt git add . && git commit -m "commit test" git push
|