git配置多个用户

利用 .gitconfig 的 includeIf 语句匹配不同的远程仓库url切换 user

配置 gitconfig

在 ~/.gitconfig 同目录下创建多个 .gitconfig.<你希望的名称> 配置文件。

在配置文件里写入以下内容:

txt 复制代码
[user]
    name = <your name>
    email = <your email>

以github 和 gitee 举例,我希望在这两个 remote 中提交代码使用不同的 user(真实场景应该是公司内部仓库应该使用真实名字提交)

txt 复制代码
[includeIf "hasconfig:remote.*.url:git@github.com:**/**/"]
	path = ~/.gitconfig.<你希望的名称>
[includeIf "hasconfig:remote.*.url:*gitee.com**/**/*"]
	path = ~/.gitconfig_gitee.<你希望的名称2>

如果习惯使用 http 链接拉取仓库,则需要这样写:

txt 复制代码
[includeIf "hasconfig:remote.*.url:https://github.com/**"]
	path = ~/.gitconfig.<你希望的名称>
[includeIf "hasconfig:remote.*.url:https://gitee.com/**"]
	path = ~/.gitconfig_gitee.<你希望的名称2>

当然也可以同时把这几条都写上去。includeIf 不支持条件或之类的语法,只能一条一条写。

进入到对应remote的代码仓库中,使用以下命令可以确认配置是否生效:

bash 复制代码
git config user.name # 输出对应的user则代表成功

注意事项

了解过 gitconfig 文件的语法后,你可能会希望这样写:

txt 复制代码
[includeIf "hasconfig:remote.*.url:git@github.com:**/*"]
    [user]
        name = <your name>
        email = <your email>
        
[includeIf "hasconfig:remote.*.url:*gitee.com**/*"]
    [user]
        name = <your name2>
        email = <your email2>

这是不行的哦,会默认使用最后一个 user。

相关文档

git-scm.com/docs/git-co...

相关推荐
驭渊的小故事9 小时前
linux 基础命令 + git 仓库创建和配置命令
linux·git
行者-全栈开发14 小时前
华为云码道 CodeArts 实测:让 AI 用 Rust 写一个 Git 仓库健康度体检台「仓衡」
git·rust·tauri·桌面应用·ai 编程·华为云码道·codearts 代码智能体
挖掘狂人3 天前
Git 从 0 到 1:用一个小项目走完 add / commit / reset / merge / rebase / push
git·后端·github
codigger3 天前
Git 三区域模型:把 add、commit、reset、merge 一次讲透
git·github·编程·编程语言
水饺编程3 天前
第1章:开发环境搭建,在 Windows 中安装 Git
linux·c语言·汇编·git·ubuntu
idanzk3 天前
Git 推送 GitHub 报 SSL_READ /src refspec main 不匹配 完整踩坑记录
git·github·ssl
星恒随风3 天前
Linux开发工具详解(二):Git版本控制、GitHub协作与GDB调试实战
linux·笔记·git·学习·github
寺中人3 天前
Xshell 完全入门指南:从安装到实战,远程连接+文件传输+会话管理全拆解
git·ssh·github·php·远程连接·xshell·运维工具
酬谢神明则必安3 天前
git学习记录01
linux·git·学习
lingchen19063 天前
版本控制 Git源代码项目管理
git