Git 用户信息配置简明教程

📝 Git 用户信息配置简明教程

1. 配置含义

  • git config user.namegit config user.email → 用来写入 提交记录作者信息

  • 它们和 GitHub 账号 是分开的,GitHub 只通过邮箱去匹配提交归属。

⚠️ 区别

  • GitHub 账号:登录/认证用(SSH Key 或 Token)。

  • Git 配置:写在 commit 里的作者名字和邮箱。


2. 配置作用域(优先级:local > global > system)

  1. local(仓库级)

    • 只对当前仓库生效(保存到 .git/config)。

    • 用于特定项目需要不同身份时。

    • 命令:

      git config user.name "项目名字"
      git config user.email "项目邮箱"
      
  2. global(全局级)

    • 作用于本机所有仓库(保存到 ~/.gitconfig)。

    • 一般个人电脑设置一次即可。

    • 命令:

      git config --global user.name "你的名字"
      git config --global user.email "你的邮箱"
      
  3. system(系统级)

    • 很少用,跳过。


3. 如何判断是否已配置

  • 查看全局配置:

    git config --global --get user.name
    git config --global --get user.email
    
  • 查看当前仓库实际生效值:

    git config --get user.name
    git config --get user.email
    
  • 查看所有值及来源:

    git config --list --show-origin
    

4. 与 GitHub 的关系

  • 想让 GitHub 正确关联提交 → user.email 必须是 GitHub 已验证邮箱 或 GitHub 提供的 noreply 隐私邮箱xxx@users.noreply.github.com)。

  • 如果邮箱不匹配 → GitHub 仍显示提交,但不会关联到你的头像/主页。


5. 常见操作

  • 首次配置(建议用全局):

    git config --global user.name "你的名字"
    git config --global user.email "你的 GitHub 已验证邮箱"
    
  • 单仓库用不同身份:

    git config user.name "公司名字"
    git config user.email "公司邮箱"
    
  • 清除配置:

    • 全局:

      git config --global --unset user.email
      
    • 本地:

      git config --unset user.email
      

6. 进阶技巧:多身份自动切换

  • ~/.gitconfig 里加条件包含:

    [user]
    name = 默认名字
    email = 默认邮箱
    
    [includeIf "gitdir:/work/company/"]
    path = ~/.gitconfig-work
    
  • ~/.gitconfig-work 写:

    [user]
    name = 公司名字
    email = 公司邮箱
    

总结

  • “是否配置过”主要指全局配置,不是项目也不是 GitHub 账户。

  • 配置一次全局 → 所有仓库默认用。

  • 特定仓库要不同身份 → 用 local 覆盖。

  • 邮箱最好用 GitHub 已验证邮箱或 noreply,保证提交正确关联。