Git命令行處理多個Github賬戶

問題引入

由于個人原因創(chuàng)建了另一個Github賬號來托管項目,當創(chuàng)建好倉庫之后將項目上傳到Github倉庫時,服務器返回以下錯誤:

ERROR: Permission to user02/TestGithub.git denied to user01.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

經(jīng)過檢查發(fā)現(xiàn)是因為我使用了SSH來克隆倉庫,所以Git會默認尋找~/.ssh目錄下名字為id_rsa的key,而不是我為此Github賬戶單獨配置的名為id_rsa_jun28的key。

當前~/.ssh目錄結構內(nèi)容如下:

id_rsa
id_rsa.pub
id_rsa_jun28
id_rsa_jun28.pub
known_hosts

解決方法

~/.ssh目錄下配置config文件,如果沒有則新建一個,添加如下內(nèi)容:

#第一個Github賬戶
Host        host01  
HostName    github.com 
User        user01  
IdentityFile    ~/.ssh/id_rsa

#第二個Github賬戶
Host        host02
HostName    github.com  
User        user02  
IdentityFile    ~/.ssh/id_rsa_jun28

其中Host的內(nèi)容為自定義名稱,在后續(xù)操作中會用到此內(nèi)容,User內(nèi)容為自己的Github用戶名,IdentityFile為相應Github賬戶使用的SSH key的文件路徑。

當配置好config文件后,相應的在命令行需要更改倉庫地址URL。

git@github.com:user02/TestGithub.git

更改為

git@host02:user02/TestGithub.git

這樣Git就會去匹配config文件里Host名稱為host02的所對應的SSH key。
最后附上Git命令行完整流程:

?  TestGithub git init
    Initialized empty Git repository in /Users/Ivan/Dev/workspace/TestGithub/.git/
?  TestGithub git:(master) echo "# TestGitHub" >> README.md
?  TestGithub git:(master) ? git add ./
?  TestGithub git:(master) ? git commit -m "First commit"
    [master (root-commit) cafede2] First commit
    1 file changed, 1 insertion(+)
    create mode 100644 README.md
?  TestGithub git:(master) git remote add origin git@host02:user02/TestGithub.git
?  TestGithub git:(master) git push -u origin master
    Counting objects: 3, done.
    Writing objects: 100% (3/3), 232 bytes | 0 bytes/s, done.
    Total 3 (delta 0), reused 0 (delta 0)
    To git@host02:user02/TestGithub.git
    * [new branch]      master -> master
    Branch master set up to track remote branch master from origin.

大功告成?。?/p>

說明,此方法僅對采用了SSH克隆倉庫的方式有效,針對Https方式本人還沒有親自測驗過,如果大家有建議或者方法,歡迎指正。

原文請見我的Github個人主頁

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

相關閱讀更多精彩內(nèi)容

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