歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> Git多帳號問題

Git多帳號問題

日期:2017/3/1 11:53:10   编辑:關於Linux

由於我平時使用的github和公司的gitlab所用的用戶名以及郵箱不同。所以要設置git多帳號登錄。

取消git全局設置

網上的教程中大都是對git進行全局設置,如下所示:

git config --global user.name "your_name"
git config --global user.email "your_email"

如果參與的項目都允許你用同一個用戶名和郵箱,這樣設置沒問題,但是在公司裡,大都會配置相應的域帳號和公司郵箱,因此我們首先需要取消git的全局設置:

git config --global --unset user.name
git config --global --unset user.email

SSH配置

假設 有兩個git項目,使用用戶名分別為A/B,用的郵箱分別為C/D。則分別進行如下:

在~/.ssh目錄下,使用ssh-keygen -C "your_email" -t rsa生成公鑰和私鑰,命名分別為id_rsa_first,id_rsa_second**(注意不按照默認配置命名)**,並需要將公鑰的內容分別上傳到git項目的服務器上。

在~/.ssh目錄下創建或修改config文件,並進行相應配置。

我的config文件配置代碼如下:

#該文件用於配置私鑰對應的服務器

#github.com上的帳號
#建立github.com的簡稱,使用這個別名做克隆和更新
Host    Github
# 主機名可用ip也可以用域名
HostName    github.com
User    kungeplay
IdentityFile    ~/.ssh/id_rsa_github

#gitlab上的帳號
Host    Gitlab
HostName    gitlab.corp.XXX.com
User    jiakun.liu
IdentityFile    ~/.ssh/id_rsa_gitlab

#oschina上的帳號
Host    Oschina
HostName    git.oschina.net
User    kungeit
IdentityFile    ~/.ssh/id_rsa_oschina

配置Git項目倉庫

針對每個項目單獨設置用戶名和郵箱:進入到各自git項目repository的相對根目錄下,通過git config配置用戶名和密碼。

比如我用git init在工作目錄中初始化新倉庫時:

mkdir Git_Hub/Shell_Practice && cd Git_Hub/Shell_Practice
git init
git config user.name "your_name"
git config user.email "your_email"
git remote add origin git@Github:/kungeplay/Shell_Practice.git
git pull origin master

再比如我用git clone從現有倉庫中克隆一個新倉庫時:

cd ~/Git/Git_Lab/
git clone git@Gitlab:jiakun.liu/second_gitlab.git
cd second_gitlab/
git config user.name "your_name"
git config user.email "your_email"
vim NewFile
git  status
git add NewFile 
git commit -m "這是一個新文件"
git push  origin master

上述的git config命令沒有加”–global”參數,因而是針對具體本地git項目repository目錄的。這些配置的優先級高於全局配置。

注意在clone或者add remote的時候,需要使用.ssh目錄中的config文件中的Host代替真實的git@remoteAddress中的remoteAddress,這樣才能讓git識別出來。比如config文件中設置的關於github上的Host為Github,則:

git clone git@Github:kungeplay/Shell_Practice.git

其他一些不涉及具體倉庫的可以全局配置。比如

git config --global color.ui true   # 彩色的git輸出
git config --global push.default simple # 執行git push沒有指定分支時,只有當前分支會被push到你使用 git pull獲取的代碼
git config --global core.autocrlf false # 讓Git不要管Windows/Unix換行符轉換的事
git config --global gui.encoding utf-8  # 避免git gui中的中文亂碼
git config --global core.quotepath off  # 避免git status顯示的中文文件名亂碼
Copyright © Linux教程網 All Rights Reserved