一般公司都会内部有 Git 之类的版本控制仓库,如果你同时有在其他远程 Git 仓库(比如 GitHub) 提交代码的习惯。此时,你就需要在同一台机器上配置多个 Git 用户。
Git 多用户配置
举个栗子: 张小天 的公司xx的 Git 仓库地址是 git.xx.com , 他公司的 Git 账号的用户名是 zhangxiaotian, 邮箱是 zhangxiaotian@xx.com。张小天 的 GitHub 用户名是 LittleZhang,邮箱是 LittleZhang@gmail.com。
张小天可以这样设置:
- 将 GitHub 的 Git 用户作为全局用户: - 1 
 2- git config --global user.name "LittleZhang" 
 git config --global user.email "LittleZhang@gmail.com"- 这个全局的配置文件路径默认是 - ~/.gitconfig
- 将 xx 公司的 Git 用户配置到 - ~/.gitconfig-work文件中去:- 1 
 2- git config -f ~/.gitconfig-work user.name "zhangxiaotian" 
 git config -f ~/.gitconfig-work user.email "zhangxiaotian@xx.com"
- 在全局配置( - ~/.gitconfig) 中使用 conditional includes 引用- ~/.gitconfig-work- 1 - git config --global includeif."gitdir:~/Work/".path .gitconfig-work - 最终,根据之前的配置,全局配置文件内容如下: - 1 
 2
 3
 4
 5- [user] 
 name = LittleZhang
 email = LittleZhang@gmail.com
 [includeIf "gitdir:~/Work/"]
 path = .gitconfig-work- gitdir表示- .git(本地带有版本控制的项目) 所在位置,- includeIf整个语句表示- ~/Work/路径下的所有的 Git 版本控制项目对应的 Git 用户信息都依据- .gitconfig-work来配置,即使用- zhangxiaotian@xx.com这个用户。更多详细用法,请参考 Git 官方文档: includes
- 把工作中的项目放在 - ~/Work/路径下即可。
此时,张小天已经完成了 Git 的多用户配置,他只需要将工作中的项目放在 ~/Work/ 目录下即可,当然了,他也可以配置多个工作路径。但是只做好 Git 配置,只能使用 http(s) 来同步仓库,每次同步时还需要输入密码。接下来就需要进行多用户的 ssh 配置
ssh 多用户配置
- 生成 Github 的 Git 用户的 ssh 公钥私钥: - 1 - ssk-keygen -t rsa -C "LittleZhang@gmail.com" -f ~/.ssh/github - 会生成私钥 - ~/.ssh/github和 公钥- ~/.ssh/github.pub
- 生成 xx 公司的 Git 用户的 ssh 公钥私钥: - 1 - ssk-keygen -t rsa -C "zhangxiaotian@xx.com" -f ~/.ssh/xx - 会生成私钥 - ~/.ssh/xx和 公钥- ~/.ssh/xx.pub
- 生成 ssh 的 config 文件用于路由不同的配置: - 1 
 2
 3
 4
 5
 6
 7- Host git.xx.com 
 HostName git.xx.com
 IdentityFile ~/.ssh/xx
 Host github.com
 HostName github.com
 IdentityFile ~/.ssh/github
- 将对应的 .pub 公钥信息添加到相对应的网站,不同的 Git 仓库网站,添加操作可能会不一样,但总体是一致的,网上有很多教程,就不再赘述了。 
- 使用 - ssh -T git@github.com或者- ssh -vT git@github.com(- -v会包含更多改命令的操作细节) 来验证是否能通过 ssh 的方式正常连接到 GitHub。同理,也可以验证公司公司能否 ssh 连接成功。
至此,张小天完成了 Git 多用户配置 和 ssh 多用户配置的所有操作。撒花 ✿✿ヽ(°▽°)ノ✿