推送到多个 GitHub 账户!
生成 SSH 密钥
对于每个帐户,生成一个单独的 SSH 密钥:
ssh-keygen -t ed25519 -C "your-email-for-first-account" -f ~/.ssh/id_ed25519_first ssh-keygen -t ed25519 -C "your-email-for-second-account" -f ~/.ssh/id_ed25519_second
将 SSH 密钥添加到代理
eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519_first ssh-add ~/.ssh/id_ed25519_second
列出现有的 SSH 密钥
运行以下命令列出您的 SSH 密钥:
ls ~/.ssh
您应该会看到类似“id_ed25519”、“id_ed25519.pub”、“id_ed25519_first”、“id_ed25519_second”或类似的文件。.pub 文件是公钥。
将公钥添加到 GitHub
将每个公钥复制到 GitHub:
cat ~/.ssh/id_ed25519_first.pub cat ~/.ssh/id_ed25519_second.pub
将这些密钥添加到**设置 > SSH 和 GPG 密钥**下的相应 GitHub 帐户。
配置 ~/.ssh/config
创建或编辑 `~/.ssh/config` 文件来定义主机别名:
nano ~/.ssh/config
添加以下行:
Host github-first HostName github.com User git IdentityFile ~/.ssh/id_ed25519_first Host github-second HostName github.com User git IdentityFile ~/.ssh/id_ed25519_second
**保存文件。**
测试 SSH 密钥
使用以下命令通过 GitHub 测试您的 SSH 密钥。
对于第一个帐户:
ssh -T git@github-first
您应该会看到如下消息:
Hi username! You've successfully authenticated, but GitHub does not provide shell access.
**也检查第二个帐户!**
如果遇到任何问题,请确保:
克隆存储库
使用所需帐户的别名:
git clone git@github-first:username/repository.git git clone git@github-second:username/repository.git
更新现有存储库的远程
如果您要切换遥控器:
git remote set-url origin git@github-first:username/repository.git git remote set-url origin git@github-second:username/repository.git
从 VS Code(或任何代码编辑器)推送代码
**1. 在 VS Code 中打开存储库文件夹。**
**2. 确保设置了正确的遥控器:**
git remote -v
**3. 提交并推送代码:**
git add . git commit -m "Your commit message" git push origin main