多GitHub并存在git提交方式
日常使用VSCode,并且有多个GitHub账号。希望不在VSCode中用特定GitHub账号登录的情况下正常推送代码。最可靠且稳定的方法是使用 SSH Key(每个账号独立)或 HTTPS+PAT(个人访问令牌)。推荐使用 SSH Key方式。
为每个 GitHub 账号生成独立 SSH Key,并用 SSH Host 别名绑定到仓库
生成 Key(示例为 work 账号):
ssh-keygen -t ed25519 -C "you@work.com" -f ~/.ssh/id_ed25519_work eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519_work
- 把 ~/.ssh/id_ed25519_work.pub 的内容复制到对应 GitHub 账号的 Settings → SSH and GPG keys。
在 ~/.ssh/config 添加 Host 别名:
Host github-work HostName github.com User git IdentityFile ~/.ssh/id_ed25519_work IdentitiesOnly yes
在本地 repo 使用别名作为 remote,注意改成实际的
work-username/repo
,某些情况下,set-url origin
可能需要改成add origin
cd /path/to/program git remote set-url origin git@github-work:work-username/repo.git
测试连接:
ssh -T git@github-work git remote -v # 检查远端状态
设置本仓库的提交作者(只影响 commit 作者信息):
git config user.name "Work Name" git config user.email "you@work.com"
此时在 VSCode 中不需要登录对应 GitHub 账户,VSCode 会使用系统的 SSH key 进行 push/pull。