同一台 Mac 管理多個 GitLab 帳號
在同一台 Mac 上同時使用兩個(或以上)GitLab 帳號(例如公司與個人)時,需要解決兩件事:
- SSH 驗證:連到 GitLab 時用哪一把金鑰(對應哪個帳號)
- Git 身分:commit 時使用的
user.name/user.email(避免 commit 作者混亂 )
做法可分兩種:僅用 SSH config + 每專案手動設 user,或 SSH config + .gitconfig 條件式設定(建議)。
核心概念
- 不同 Host 名稱 → 不同 SSH Key:在
~/.ssh/config裡為同一個gitlab.com設定多個「虛擬 Host」(如gitlab.com-personal、gitlab.com-work),各自指定不同的IdentityFile。 - Clone / remote URL:clone 或設定 remote 時改用虛擬 Host,例如
git@gitlab.com-work:group/project.git,SSH 就會自動用對應的金鑰。 - 建議:用 .gitconfig 的
includeIf依「目錄」或「remote URL」自動帶入對應的user.name/user.email,不需每個 repo 手動設一次。
共通步驟 1:為不同帳號產生獨立 SSH Key
為每個帳號各產生一對金鑰,檔名區分清楚。
# 個人帳號
ssh-keygen -t ed25519 -C "personal@email.com" -f ~/.ssh/id_ed25519_personal
# 公司帳號
ssh-keygen -t ed25519 -C "work@company.com" -f ~/.ssh/id_ed25519_work
若詢問 passphrase,可直接 Enter 跳過。
共通步驟 2:把公鑰加到對應的 GitLab 帳號
- 複製公鑰:
pbcopy < ~/.ssh/id_ed25519_personal.pub(個人)、pbcopy < ~/.ssh/id_ed25519_work.pub(公司) - 登入各 GitLab 帳號,Settings → SSH Keys,貼上並儲存。
共通步驟 3:設定 SSH Config
讓 SSH 依「虛擬 Host」選擇金鑰。編輯或新增 ~/.ssh/config:
nano ~/.ssh/config
內容範例:
# 個人 GitLab
Host gitlab.com-personal
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_ed25519_personal
# 公司 GitLab
Host gitlab.com-work
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_ed25519_work
之後 clone / remote 都要用上述 Host 名稱(見下方「使用方式」)。
作法 A:僅 SSH config + 每專案手動設 user(不建議)
- Clone:改用虛擬 Host
- 個人:
git clone git@gitlab.com-personal:username/project.git - 公司:
git clone git@gitlab.com-work:company/project.git
- 個人:
- 已存在的專案:改 remote
git remote set-url origin git@gitlab.com-personal:username/project.git - 身分:每個專案目錄下手動設一次,否則會用到全域的 name/email:
cd /path/to/personal_project
git config user.name "Your Name"
git config user.email "personal@email.com"
缺點:每個 repo 都要記得設一次,容易漏設或設錯。