Github 如何在本地配置多个帐号?

18 min read

要在本地配置多个GitHub帐号,可以按照以下步骤操作:

  1. 生成新的SSH密钥对:

    • 打开终端(Linux和macOS)或Git Bash(Windows)。
    • 输入以下命令,并替换邮箱地址为新GitHub帐号的邮箱地址:
      ssh-keygen -t rsa -C "[email protected]"
      
    • 一路回车,直到密钥对生成完毕。
  2. 将新生成的SSH密钥添加到SSH代理:

    • 运行以下命令来启动ssh-agent:
      eval "$(ssh-agent -s)"
      
    • 添加SSH私钥到ssh-agent:
      ssh-add ~/.ssh/id_rsa
      
  3. 将新的SSH公钥添加到新的GitHub帐号上:

    • 复制SSH公钥到剪贴板:
      cat ~/.ssh/id_rsa.pub | pbcopy
      
    • 登录GitHub,进入新帐号的设置页面。
    • 点击"SSH and GPG keys"(或类似的选项)。
    • 点击"New SSH key"(或类似的按钮)。
    • 粘贴刚才复制的SSH公钥到"Key"字段中,设置一个适当的标题,然后点击"Add SSH key"以保存。
  4. 创建或编辑配置文件 ~/.ssh/config:

    • 在终端中输入以下命令打开或创建配置文件:
      nano ~/.ssh/config
      
    • 添加以下内容到配置文件中,代替account1account2为你的GitHub帐号用户名,并分别使用刚才生成的SSH私钥路径:
      # Account 1
      Host github.com-account1
          HostName github.com
          User git
          IdentityFile ~/.ssh/account1_rsa
      
      # Account 2
      Host github.com-account2
          HostName github.com
          User git
          IdentityFile ~/.ssh/account2_rsa
      
    • 使用Ctrl + X保存并退出。
  5. 配置Repository的远程仓库地址:

    • 在终端中进入想要克隆的项目文件夹。
    • 执行以下命令,将仓库地址中的github.com替换为github.com-account1github.com-account2,分别对应不同的GitHub帐号:
      git remote set-url origin [email protected]:username/repo.git
      
      # 或
      git remote set-url origin [email protected]:username/repo.git
      

现在你就可以使用不同的GitHub帐号在本地进行操作了。当使用git push或其他相关命令时,Git将根据配置文件中的设置,自动使用相应的SSH密钥。