如何在本地配置多個GitHub賬號

在平時的工作中,經(jīng)常會遇到需要使用兩個GitHub賬戶,一個自己的賬戶,一個工作的賬戶。 所以接下來講解如何在本地配置兩個GitHub賬號,保證可以同時使用。

1. 創(chuàng)建ssh密鑰,在GitHub上綁定密鑰

有兩個不同的GitHub賬號,所以需要有兩個ssh密鑰。

1.1 分別使用兩個GitHub 的郵箱,生成兩個ssh密鑰文件,需要給不同的賬號取不同的名字。在執(zhí)行命令的過程中需要一直回車就行。

ssh-keygen -t rsa -f ~/.ssh/id_rsa -C "personal@outlook.com"
ssh-keygen -t rsa -f ~/.ssh/id_rsa_work -C "work@outlook.com"

1.2 生成的密鑰存放在 /Users/name/.ssh 路徑下,打開公鑰文件 id_rsa.pub/id_rsa_work.pub
復(fù)制所有內(nèi)容,在GitHub上打開Setting -> SSH and GPG keys -> add SSH key,將復(fù)制的內(nèi)容粘貼在里邊,保存。

2. 創(chuàng)建Config文件,配置多個賬號

2.1 在/Users/name/.ssh路徑下,創(chuàng)建一個config文件,添加下邊代碼在config文件中。

  • Host: 在Clone倉庫的時候使用,默認(rèn)的使用github.com, 所以要給工作的GitHub賬號起一個不一樣的Host
  • IdentityFile: 填寫對應(yīng)賬號的私鑰的文件路徑
# Personal account
Host github.com
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa
   
# Work account
Host workgithub.com  
   HostName github.com
   User git
   IdentityFile ~/.ssh/id_rsa_work

2.2 執(zhí)行以下命令來開啟 ssh 服務(wù)

ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_rsa_work

2.3 驗證ssh服務(wù)是否開啟,需要注意的是,-T 后邊跟的內(nèi)容就是 git@"config中Host的內(nèi)容",也就是clone倉庫的內(nèi)容。

ssh -T git@github.com
ssh -T git@workgithub.com

如果開啟成功,就會看到如下的內(nèi)容,測試成功之后就可以工作了。

3. 使用的Git命令

3.1 Clone代碼:

  • git@github.comgit@"config中Host的內(nèi)容",所以工作的賬戶就是git@workgithub.com
  • test/test.git 指的就是倉庫的地址
git clone git@github.com:test/test.git
git clone git@workgithub.com:test/test.git 

3.2 在對應(yīng)的倉庫路徑下配置user和email

git config user.email "personal@outlook.com"
git config user.name "personal"
git config user.email "work@outlook.com"
git config user.name "work"
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容