git多账号切换

  • 多个github的账号,不同的账号对应不同的repo,需要push的时候自动区分账号

  • 多个git的账号,对应不同的仓库(github,bitbucket,私有gitla),需要push的时候自动区分账号

多个git账号

  1. 生成ssh key

先假设我有两个账号,一个是github上的,一个是公司gitlab上面的。先为不同的账号生成不同的ssh-key

(windows 在C:\Users\username\.ssh)
ssh-keygen -t rsa -f ~/.ssh/id_rsa_gitlab -c xxx@gmail.com
ssh-keygen -t rsa -f ~/.ssh/id_rsa_github -c xxx@gmail.com
  1. 把对应得到的id_rsa_github和id_rsa_gitlab.pub,分别把添加到github和gitlab中

  2. 编辑~/.ssh/config, 设定不同的git 服务器对应不同的key

    # Default github user(first@mail.com),注意User项直接填git,不用填在github的用户名
    Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_github
    
    # second user(second@mail.com)
    # 建一个gitlab别名,新建的帐号使用这个别名做克隆和更新
    Host 10.214.224.201
    HostName 10.214.224.201
    User work
    IdentityFile ~/.ssh/id_rsa_gitlab
    
  3. 检查是否对应: ssh -vT git@github.com

多个github账号

所有步骤相同,只有步骤3不同,ssh区分账号,其实靠的是HostName这个字段,因此如果在github上有多个账号,很容易的可以把不同的账号映射到不同的HostName上就可以了。比如我有A和B两个账号, 先按照步骤一生成不同的key文件,再修改~/.ssh/config 内容应该是这样的。

# Default github user(A@mail.com),注意User项直接填git,不用填在github的用户名
Host A.github.com
 HostName github.com
 User git
 IdentityFile ~/.ssh/id_rsa_github_A

# second user(B@mail.com)
# 建一个gitlab别名,新建的帐号使用这个别名做克隆和更新
Host A.github.com
 HostName github.com
 User git
 IdentityFile ~/.ssh/id_rsa_github_B

更换提交地址,直接更改 repo/.git/config 里面的url即可

修改:
git@github.com:testA/gopkg.git
为:
git@A.github.com:testA/gopkg.git

一个repo同时推送到多个不同的仓库

直接更改 repo/.git/config 里面的url即可,把里面对应tag下的url增加一个就可以了。例:

[remote "GitHub"]
url = git@github.com:elliottcable/Paws.o.git
fetch = +refs/heads/*:refs/remotes/GitHub/*
[branch "Master"]
    remote = GitHub
    merge = refs/heads/Master
[remote "Codaset"]
    url = git@codaset.com:elliottcable/paws-o.git
    fetch = +refs/heads/*:refs/remotes/Codaset/*
[remote "Paws"]
    url = git@github.com:Paws/Paws.o.git
    fetch = +refs/heads/*:refs/remotes/Paws/*
[remote "Origin"]
    url = git@github.com:Paws/Paws.o.git # 推送到github
    url = git@codaset.com:elliottcable/paws-o.git #推送到codaset