如何在一台机器上管理多个 Github 账号

场景

在一台电脑上,有两个Repository ,它们分属两个不同的 Github 账号。

步骤

为 Repository 配置 Github 的 Git 账号

使用终端进入到 Repository A目录下,配置 Git 账号

$ git config user.name "user_a"
$ git config user.email "user_a@gmail.com"

使用终端进入到 Repository B 目录下,配置 Git 账号

$ git config user.name "user_b"
$ git config user.email "user_b@gmail.com"

为不同的 Github 用户生成 SSH 密钥

为 user_a 生成 SSH 密钥,密钥名为 user_a_id_rsa

$ ssh-keygen -t rsa -C "user_a@gmail.com"

同样操作,为 user_b 生成 SSH 密钥,密钥名为 user_b_id_rsa

$ ssh-keygen -t rsa -C "user_b@gmail.com"

配置多账户的 SSH 匹配

在 .ssh 目录下,新建 config 文件,配置多用户的密钥:

host user_a_github.com
    Hostname github.com 
    User git 
    IdentityFile ~/.ssh/user_a_id_rsa  

host user_b_github.com
    Hostname github.com 
    User git 
    IdentityFile ~/.ssh/user_b_id_rsa

添加新的私钥到 ssh-agent 缓存中

$ eval "$(ssh-agent -s)"
$ ssh-add ~/.ssh/user_a_id_rsa
$ ssh-add ~/.ssh/user_b_id_rsa

修改 Repository 的 push 地址

对 Repository 中 .git/config 的 url 字段值 git@github.com 修改。

修改 Repository A 的 push 地址:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    url = git@user_a_github.com:*********/***********.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[user]
    name = user_a
    email = user_A@gmail.com

修改 Repository A 的 push 地址:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    url = git@user_b_github.com.com:******/******.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[user]
    name = user_b
    email = user_b@gmail.com

至此,完毕。

一些命令

# 检查当前用户
ssh -vT git@github.com
# 检查当初密钥
ssh-add -l
# 添加密钥
# 删除密钥
ssh-add -d /Users/****/.ssh/id_rsa
# 查看 git config 配置
git config --list
git
本作品采用《CC 协议》,转载必须注明作者和本文链接
Write the code.Change the world.
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!