适用于:在不同项目中使用不同 Git 用户名和邮箱(如个人 vs 公司)时,自动切换身份,防止误提交。


✨ 场景说明

你在本地维护多个 Git 仓库:

  • ~/code/work/ 中是公司项目,需用公司邮箱;
  • 其他路径中是个人项目,需用个人邮箱。

手动切换 git config user.email 容易出错,因此使用 Git 的 includeIf 机制自动切换身份。


📦 最终效果

  • 进入 ~/code/work/xxx,自动使用公司 Git 身份;
  • 在其他地方使用默认个人 Git 身份;
  • 所有切换全自动,无需手动设置。

🧱 步骤说明

1. 配置全局 Git 默认身份(通常为个人身份)

编辑 ~/.gitconfig

1
2
3
4
5
6
[user]
name = Your Name
email = [email protected]

[includeIf "gitdir:/Users/kunl/code/work/"]
path = /Users/kunl/.gitconfig-work

注意:路径末尾必须有 /,表示匹配该目录下的所有仓库。


2. 创建工作路径下的专属 Git 配置文件

创建文件 ~/.gitconfig-work,内容如下:

1
2
3
[user]
name = Kun L
email = [email protected]

该配置只在进入 /Users/kunl/code/work/** 路径下的 Git 仓库时生效。


3. 验证配置是否生效

进入某个工作目录下的项目:

1
2
3
cd ~/code/work/my-company-project
git config user.email
# 输出应为:[email protected]

切换到非工作目录:

1
2
3
cd ~/code/personal-project
git config user.email
# 输出应为:[email protected]

✅ 优势

  • ✅ 完全自动切换,无需手动设置;
  • ✅ 防止提交时使用了错误身份;
  • ✅ 无侵入性,不影响其他配置;
  • ✅ 可按多路径配置多个身份(例如 ~/.gitconfig-openai~/.gitconfig-side-projects 等)。

🛠️ 高级玩法:多身份组合

你可以在 ~/.gitconfig 中配置多个路径自动 include:

1
2
3
4
5
[includeIf "gitdir:/Users/kunl/code/work/"]
path = /Users/kunl/.gitconfig-work

[includeIf "gitdir:/Users/kunl/code/open-source/"]
path = /Users/kunl/.gitconfig-oss

每个 .gitconfig-* 中配置对应身份。


🧼 可选清理指令

若之前误设置了全局邮箱为公司:

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

🧪 附:手动设置当前仓库身份(不推荐但可用)

1
2
git config user.name "Kun L"
git config user.email "[email protected]"

这只会影响当前项目,不影响其他目录。


📎 总结

方案 自动化程度 推荐度
includeIf + 子配置 💯 全自动 ⭐⭐⭐⭐⭐
手动在项目设置 user.name/email 半自动 ⭐⭐
全局反复改动 容易出错

如需快速初始化配置,可创建 shell 脚本自动生成 .gitconfig-work 和 include 配置,想要我帮你写一份脚本也可以 👍