在 Mac / Linux 下,設定多個 Github user(使用 SSH Key)

許聖泉 Michael Hsu
3 min readApr 12, 2021

--

建立 SSH Key

並且存在 .ssh 底下不同的資料夾

ssh-keygen -t ed25519 -C "michael@personal.com"
ssh-keygen -t ed25519 -C "michael@company.com"

資料夾會是像這樣

.ssh
|-michael@personal.com
|-id_ed25519
|-id_ed25519.pub
|-michael@company.com
|-id_ed25519
|-id_ed25519.pub

將這些 SSH Key 設定到 https://github.com 中,這邊就不在說明怎麼設定囉。

參考:https://docs.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh

設定 SSH config

在 .ssh 底下建立 config 這支檔案

Host            github.com
Hostname github.com
User git
Match Host github.com exec "[ $(git config user.email) = michael@company.com ]"
IdentityFile ~/.ssh/michael@company.com/id_ed25519
Host github.com
IdentityFile ~/.ssh/michael@personal.com/id_ed25519

建立 .gitconfig.d 來管理不同 git user 設定檔

在家目錄建立 .gitconfig.d 這個資料夾

建立 michael@company.com.inc

[user]
email = michael@company.com
name = Michael

編輯 .gitconfig

回到家目錄編輯 .gitconfig

[user]
email = michael@personal.com
name = Michael
[includeIf "gitdir:/Users/michael/workspace/company/"]
path = /Users/michael/.gitconfig.d/michael@company.com.inc

.gitconfig 內其他的設定不用動

[user] 這邊直接設定 Personal 的設定,當作是 Global 的設定檔,只要是工作目錄以外的都使用這個 Config。

另外加上了 [includeIf]

其中的 “gitdir:/Users/michael/workspace/company/” 表示,在這個目錄下所有的 Git 都會套用後方 Path 的設定。

意思就是,/Users/michael/workspace/company/ 之後的目錄,包含子目錄內的所有專案,如果有使用 Git 的話,都會使用 /Users/michael/.gitconfig.d/michael@company.com.inc 內的設定,也就是 git user.emal = michael@company.comgit user.name = Michael

--

--

許聖泉 Michael Hsu
許聖泉 Michael Hsu

No responses yet