在平時的工作中,經(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.com是git@"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"