工作中经常需要用不同的 Git 账号,每次 clone 和 push 都要手动指定账号很烦。本文教你一次配置好,以后再也不用操心。
核心原理:通过 SSH 配置文件为不同的域名分配不同的密钥对。
第一步:生成多个 SSH Key
ssh-keygen -t ed25519 -C your_email@company.com -f ~/.ssh/id_ed25519_company
ssh-keygen -t ed25519 -C your_email@gmail.com -f ~/.ssh/id_ed25519_personal
第二步:添加到 SSH Agent
eval “$(ssh-agent -s)”
ssh-add ~/.ssh/id_ed25519_company
ssh-add ~/.ssh/id_ed25519_personal
第三步:配置 SSH config
Host github-personal
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_personal
Host github-work
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_company
第四步:使用不同的 remote
git remote add origin git@github-work:company/repo.git
git remote add origin git@github-personal:yourname/repo.git
常见问题
Q: 为什么有时候 clone 还是要输密码?
A: 检查是否使用了 https URL 而不是 SSH URL。确保 remote 是 git@ 开头。
Q: git@github.com 被拒绝?
A: 可能是多个 key 被同时尝试。确保 config 文件 Host 名与 clone URL 对应。
SSH Config 是 Git 多账号管理的标准解法,配置一次,永久省心。