Git 首次使用完整设置指南

1 git config 的三层级与文件路径

Git 使用 git config 命令读写配置,配置值可存在 三种层级,后者会覆盖前者:

层级 影响范围 默认文件 读写命令示例
系统级 --system 整台机器所有用户、所有仓库 Linux/macOS → /etc/gitconfig
Windows → %ProgramData%\Git\config(Vista 及以后)
Windows XP → C:\Documents and Settings\All Users\Application Data\Git\config
sudo git config --system <键> <值>
全局级 --global 当前用户的所有仓库 ~/.gitconfig ~/.config/git/config
Windows → C:\Users\\.gitconfig
git config --global <键> <值>
本地级 --local(默认) 当前仓库 <仓库>/.git/config git config <键> <值>
  • 必须位于 Git 仓库内部时,--local 或默认写入才有效。

  • 优先级:本地 > 全局 > 系统。

  • 查看所有键及其来源文件

    git config --list --show-origin
    

1.1 Windows 专属补充

  • Git 仍会尝试读取“Unix 风格”的 /etc/gitconfig,该路径相对于 MSys 根目录(即安装 Git for Windows 时所选位置)。

  • 如果你使用 Git for Windows 2.x 及更高版本,还存在系统级文件

    • XPC:\Documents and Settings\All Users\Application Data\Git\config
    • Vista+C:\ProgramData\Git\config
      管理员 身份执行:
    git config -f "C:\ProgramData\Git\config" --system <键> <值>
    

2 设置个人身份(每台电脑必须做)

git config --global user.name "Your Name"
git config --global user.email [email protected]
  • --global 只需一次,随后所有仓库都会使用。
  • 若某项目需不同身份,进入该仓库 后再运行 不带 --global 的同命令覆盖即可。
  • 许多 GUI(SourceTree、GitKraken 等)启动时也会提示填写此信息。

3 指定默认文本编辑器

Git 需要你输入提交说明、合并信息等时会调用编辑器;若无配置则使用系统默认(Linux 常为 vi,Windows 为 notepad.exe)。

3.1 Unix-like(Linux/macOS)

git config --global core.editor vim      # 或 emacs / nano ...

3.2 Windows(必须写绝对路径并用引号)

git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"

Note
Vim、Emacs、Notepad++ 是开发者常用编辑器;若你使用其它程序,请到官方文档查对应启动参数并通过 git config core.editor 设置。
Warning
如果编辑器路径或参数错误,Git 调用时可能异常中断,导致提交操作半途而废,界面会让人摸不着头脑。

4 自定义仓库默认分支名(Git ≥ 2.28)

Git init 旧版默认创建 master 分支。从 2.28 起可预设其它名称,例如团队统一用 main

git config --global init.defaultBranch main

5 检查配置

5.1 列出全部可见键值

git config --list

若同一键在多个文件出现,会看到多行;Git 取 最后一次 读到的值作为生效值。

5.2 查询单个键

git config user.name

5.3 查找生效来源文件

git config --show-origin rerere.autoUpdate
# 输出示例:
# file:/home/youruser/.gitconfig    false

6 命令速查表

目标 命令
设全局姓名 git config --global user.name "Your Name"
设全局邮箱 git config --global user.email [email protected]
设默认编辑器 Vim git config --global core.editor vim
设默认分支 main git config --global init.defaultBranch main
全量查看(含来源) git config --list --show-origin
定位某键来源 git config --show-origin core.editor

✅ 本节小结

  1. 三层级文件 理解透,排错有依据。
  2. 姓名 / 邮箱 为每次提交盖上“身份证章”,先配才不留隐患。
  3. 编辑器 直接决定交互体验,Windows 需绝对路径加引号。
  4. 若团队不用 master,提早设置 init.defaultBranch 统一规范。
  5. 配置命令 幂等可覆盖,用同一键再执行一次即可修改,无需手动编辑文件。

完成以上步骤,你的 Git 环境已完全就绪 —— 马上 git initgit clone 开启版本控制之旅吧!

你可能感兴趣的:(Git 首次使用完整设置指南)