问题场景:在工作中,都会有一个工作的Git帐号(公司Gitlab),而空闲时间做的个人东西又想放进Github里面,这时候就需要配置两个帐号和服务器。
设置步骤:
创建两个SSH key:
个人用的key,名字默认id_rsa即可
ssh-keygen -t rsa -C "youremail@example.com"
公司用的key,名字id_rsa_company即可
ssh-keygen -t rsa -C "youremail@example.com"
添加新密钥到SSH agent,因为默认只读取id_rsa,为了让SSH识别新的私钥,需将其添加到SSH agent中:
ssh-add ~/.ssh/id_rsa_company
该命令如果报错:Could not open a connection to your authentication agent.无法连接到ssh agent,可执行ssh-agent bash命令后再执行ssh-add命令。
修改config文件,若~/.ssh/目录下不存在config文件,则新建一个,内容如下:
# GitHub Host github.com HostName github.com PreferredAuthentications publickey IdentityFile ~/.ssh/id_rsa # Company Host xxx.com HostName xxx.com PreferredAuthentications publickey IdentityFile ~/.ssh/id_rsa_company
添加秘钥到个人的Github和公司的Gitlab上:
把~/.ssh/id_rsa.pub的内容添加到Github的SSH keys中,把~/.ssh/id_rsa_company.pub的内容添加到Gitlab的SSH keys中
设置全局用户名和邮箱:
git config --global user.name "github's name" git config --global user.email "github's email"
在特定的repo下执行下面的命令,生成区别于全局设置的user.name和user.email:
git config user.name "name" git config user.email "email"
设置完成,git clone 指定仓库即可。
Git多账号管理
最新推荐文章于 2025-06-26 17:27:41 发布