git多用户配置

169 阅读1分钟

git多用户配置

场景

在git的使用中,经常会出现这种情况:在公司有一个git账户,github上有个人账户,希望在同一台电脑针对不同的项目使用不同的账号。
此时就需要进行git多用户配置

  1. 创建用户

    • 全局用户

      git config --global user.name "globalUser"
      git config --global user.email "global@email.com"
      
    • 局部用户
      cd 到项目所在目录,或在项目目录打开git bash

      git config user.name "workUser"
      git config user.email "work@email.com"
      
  2. 生成ssh-key
    针对不同账户保存不同文件名

    ssh-keygen -t rsa -C "global@email.com"
    Enter file in whict to save the key (/c/Users/Administrator/.ssh/id_rsa): id_rsa
    ssh-add ~/.ssh/id_rsa
    
    ssh-keygen -t rsa -C "work@email.com"
    Enter file in whict to save the key (/c/Users/Administrator/.ssh/id_rsa): work_id_rsa
    ssh-add ~/.ssh/work_id_rsa
    
  3. 将生成的ssh-key添加到github和公司git仓库
    查看密钥,注意添加后缀为pub的key

    cat ~/.ssh/id_rsa.pub
    
  4. ~/.ssh目录下添加config文件

    cd ~/.ssh
    vim config
    
    #github global@gmail.com
    host github.com  #别名,随便定 后面配置地址有用
        Hostname github.com #要连接的服务器
        User global #用户名
        IdentityFile ~/.ssh/id_rsa  #密钥文件的地址,注意是私钥
     
    #github work
    host work #别名,随便定
        Hostname 公司git仓库地址
        Port 公司git仓库端口
        User work
        IdentityFile ~/.ssh/work_id_rsa
    
  5. 验证是否成功

    ssh -T git@github.com
    ssh -T git@公司git仓库地址