停止使用个人邮箱推送工作代码:在 Windows 上管理多个 GitHub 账户的终极指南
Source: Dev.to
The Concept: SSH Keys & Aliases
Git 默认使用单一的全局用户。要在不同账户之间切换,需要:
- 两个独立的 SSH 密钥(一个用于个人,一个用于工作)。
- 一个 SSH 配置文件,将别名(例如
github-work)映射到相应的密钥。
Step 1: Generate Unique SSH Keys
# Create the .ssh directory if it doesn't exist
mkdir "$HOME\.ssh"
cd "$HOME\.ssh"
Personal key
ssh-keygen -t ed25519 -C "personal@gmail.com" -f id_personal
Work key
ssh-keygen -t ed25519 -C "work@company.com" -f id_work
Note: Do not overwrite your existing default key (
id_rsa).
Step 2: The “Eval” Problem (Windows Solution)
通常的 eval $(ssh-agent -s) 命令在 PowerShell 中经常失效。改为启用内置的 Windows ssh-agent 服务,使其在重启后仍然保持运行。
# Run PowerShell as Administrator
Get-Service -Name ssh-agent | Set-Service -StartupType Automatic
Start-Service ssh-agent
添加密钥(可以在普通的 PowerShell 窗口中执行):
ssh-add $HOME\.ssh\id_personal
ssh-add $HOME\.ssh\id_work
验证两把密钥是否已加载:
ssh-add -l
Step 3: Upload Keys to GitHub
- 打开 Personal 公钥文件(
id_personal.pub),复制其中内容。 - 在 GitHub → Settings → SSH and GPG keys,点击 New SSH key,粘贴密钥并保存。
- 在公司的 GitHub 账户上,用 Work 公钥(
id_work.pub)重复上述步骤。
Step 4: The Magic Config File
在 $HOME\.ssh\ 下创建一个名为 config(无扩展名)的文件,内容如下:
# Personal Account – Default
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_personal
# Work Account – Alias
Host github-work
HostName github.com
User git
IdentityFile ~/.ssh/id_work
Step 5: Cloning & Configuring Repositories
-
Personal projects: 正常克隆即可。
git clone git@github.com:username/repo.git -
Work projects: 使用别名
github-work替代github.com。git clone git@github-work:company/repo.git
Set Your Local Identity
克隆工作仓库后立即配置本地 Git 身份,以免提交时使用错误的邮箱:
git config user.name "Your Work Name"
git config user.email "work@company.com"
Bonus: Fixing a Commit Pushed with the Wrong Email
如果已经推送了使用个人邮箱的提交,可以在不删除仓库的情况下重写它。
-
更新本地 Git 配置(如果尚未设置):
git config user.email "work@company.com" -
修改最近一次提交,重置作者信息:
git commit --amend --reset-author --no-edit -
强制推送已修正的提交:
git push -f origin main
Conclusion
在 Windows 上配置多个 GitHub 账户大约只需 10 分钟,却能帮你避免无尽的 “Permission denied” 错误以及身份混淆的尴尬。只要 ssh-agent 服务和 SSH 配置文件就位,一切都会在后台顺畅运行。
Happy coding! 🚀