Loading

Git 多账号环境隔离

以下内容使用环境均为 Windows

在实际开发中,常见需求包括:

  • 同时使用 公司账号 / 个人账号
  • 不想手动切换 user.name / user.email

目标是实现:自动根据工作目录切换账号

配置 SSH 多账号

编辑:

~/.ssh/config
示例(私服 + 多账号)
# 私服 - 工作账号
Host github-work
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_work

# 私服 - 个人账号
Host github-personal
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_personal
验证
ssh -T github-work -p 3022

成功标志:

successfully authenticated with the key

按目录自动切换 Git 身份

编辑:

~/.gitconfig
  • 必须使用 绝对路径
  • 使用 / 而不是 \
  • 使用 /** 匹配子目录
  • 建议加 i(忽略大小写)

配置示例

[includeIf "gitdir/i:D:/study/**"]
    path = C:/Users/admin/.gitconfig_personal

[includeIf "gitdir/i:D:/work/**"]
    path = C:/Users/admin/.gitconfig_work

个人配置

# ~/.gitconfig_personal
[user]
    name = your-personal-name
    email = your-personal@email.com

工作配置

# ~/.gitconfig_work
[user]
    name = your-work-name
    email = your-work@company.com

验证

git config --show-origin --get-regexp user

必须看到:

file:C:/Users/admin/.gitconfig_self     user.name xxx
file:C:/Users/admin/.gitconfig_self     user.email xxx@gmail.com
posted @ 2026-04-12 16:27  plum_wink  阅读(26)  评论(0)    收藏  举报