• Home
  • Articles
    • 日志
    • 妍小言
    • 舒小书
    • 浩然说
    • 生活日记
  • All Tags

Git多账户管理

15 Feb 2017

Reading time ~1 minute

很多公司都使用Git作为版本管理工具,今天主要记录下自己如何把工作的Git账号和私人的GitHub账号同时管理,随意切换。

1. 新建SSH-KEY

  • 使用命令 ssh-keygen -t rsa -C "mine@email.com"
    • 为的个用户新建SSH-Key直接全部回车即可(默认存储文件)
    • 第二个用户的SSH-Key与第一个用户基本相同,但注意需指定存储文件,如:Enter file in which to save the key (/c/Users/Administrator/.ssh/id_rsa): id_rsa_mine
  • 生成后的文件结构基本如下:
eddydemac:.ssh eddy$ pwd
/Users/eddy/.ssh
-rw-------   1 eddy  staff  3243  1 14 22:46 id_rsa
-rw-r--r--   1 eddy  staff   747  1 14 22:46 id_rsa.pub
-rw-r--r--   1 eddy  staff   747  1 14 22:23 id_rsa.pub_eddy
-rw-------   1 eddy  staff  3243  1 14 22:23 id_rsa_eddy
-rw-------   1 eddy  staff  1679  1  6 18:53 id_rsa_mine
-rw-r--r--   1 eddy  staff   400  1  6 18:53 id_rsa_mine.pub

2. 将新密钥添加到SSH Agent中

  • SSH Agent默认只能读取id_rsa私钥
  • 将新生成的第二把私钥添加到SSH Agent中
    • 指令:ssh-add ~/.ssh/id_rsa_mine

3. 配置config文件

eddydemac:.ssh eddy$ cd ~/.ssh/
eddydemac:.ssh eddy$ vi config
Host github.com
    HostName github.com
    User git
    IdentityFile /Users/eddy/.ssh/id_rsa
Host github3
    HostName github.com
    User git
    IdentityFile /Users/eddy/.ssh/id_rsa_mine

4. 将新建的公钥添加到另一个GitHub中

5. 全局账户切换

  • 配置完上述步骤你已经可以使用不同身份来clone并管理下GitHub中的项目
    • 使用方式1:git clone git@github.com:Justice-love/spi.git
    • 使用方式2:git clone git@github3:Justice-love/spi.git
  • 切换git全局用户标识(user.name/user.email)
#!/bin/bash
if [[ $1 == 'work' ]];
  then
    echo 'change to work'
    git config --global user.name "work.userName"
    git config user.name
    git config --global user.email work@email.com
    git config user.email
elif [[ $1 == 'home' ]]; then
  echo 'change to home'
  git config --global user.name "home.userName"
  git config user.name
  git config --global user.email home@email.com
  git config user.email
elif [[ $1 == 'look' ]]; then
  git config user.name
  git config user.email
fi


gittool