跳转到内容
关系图谱

Git config 与配置详解

2,978 字 12 分钟

属性 1
status
学习中

Git config 与配置详解

git config 是 Git 的配置管理命令,控制着 Git 的几乎所有行为——从用户身份、编辑器选择到合并策略、性能优化。掌握配置是高效使用 Git 的基础。

一句话理解

Git 配置分三层:系统级 > 用户级 > 仓库级,优先级从低到高,仓库级配置覆盖用户级。


配置层级

三层配置体系

层级标志文件位置适用范围
系统级--system/etc/gitconfig所有用户所有仓库
用户级--global~/.gitconfig~/.config/git/config当前用户所有仓库
仓库级--local.git/config当前仓库
Worktree--worktree.git/config.worktree当前 worktree
bash
# Windows 上的路径
# 系统级: C:\Program Files\Git\etc\gitconfig
# 用户级: C:\Users\<用户名>\.gitconfig
# 仓库级: <repo>\.git\config

# 查看所有配置及其来源
git config --list --show-origin
# file:C:/Users/admin/.gitconfig    user.name=Your Name
# file:.git/config                  core.bare=false

# 查看某个配置的来源
git config --show-origin user.name
# file:C:/Users/admin/.gitconfig    Your Name

配置文件格式

ini
# .gitconfig 使用 INI 格式
[user]
    name = Your Name
    email = your@email.com

[core]
    editor = code --wait
    autocrlf = true

[alias]
    st = status
    co = checkout

# 条件包含(按目录区分配置)
[includeIf "gitdir:~/work/"]
    path = ~/.gitconfig-work

[includeIf "gitdir:~/personal/"]
    path = ~/.gitconfig-personal

必备配置

用户身份

bash
# 设置全局用户名和邮箱(必须!)
git config --global user.name "Your Name"
git config --global user.email "your@email.com"

# 为特定仓库设置不同身份(如工作 vs 个人)
cd ~/work/project
git config user.name "Work Name"
git config user.email "work@company.com"
邮箱与 GitHub 关联

GitHub 通过提交邮箱关联账户。如果邮箱不匹配,提交不会显示在你的贡献图上。

bash
# 使用 GitHub 的 noreply 邮箱(保护隐私)
git config --global user.email "123456+username@users.noreply.github.com"

条件配置(多身份管理)

bash
# ~/.gitconfig — 全局配置
[user]
    name = Personal Name
    email = personal@email.com

# 工作目录下自动切换身份
[includeIf "gitdir:C:/Users/admin/work/"]
    path = C:/Users/admin/.gitconfig-work

# ~/.gitconfig-work — 工作配置
[user]
    name = Work Name
    email = work@company.com
[core]
    sshCommand = ssh -i ~/.ssh/work_key

# 验证
cd ~/work/project
git config user.email   # work@company.com
cd ~/personal/project
git config user.email   # personal@email.com

编辑器配置

bash
# VS Code
git config --global core.editor "code --wait"

# Vim
git config --global core.editor "vim"

# Neovim
git config --global core.editor "nvim"

# Sublime Text
git config --global core.editor "subl --wait"

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

# 这些编辑器用于:
# - git commit(不带 -m 时)
# - git rebase -i
# - git merge(冲突时)
# - git config --edit

换行符处理

bash
# Windows 上(推荐)
git config --global core.autocrlf true
# checkout 时 LF → CRLF
# commit 时 CRLF → LF

# macOS/Linux 上
git config --global core.autocrlf input
# checkout 时不转换
# commit 时 CRLF → LF

# 完全禁用
git config --global core.autocrlf false
# 不做任何转换(需要 .gitattributes 配合)
推荐使用 .gitattributes 而非 autocrlf

.gitattributes 是仓库级配置,跟随代码提交,确保所有开发者一致:

# .gitattributes
* text=auto
*.sh text eol=lf
*.bat text eol=crlf
*.png binary

详见 .gitignore 与 .gitattributes


核心配置详解

core 配置

bash
# 编辑器
git config --global core.editor "code --wait"

# 分页器(查看 log/diff 时的分页工具)
git config --global core.pager "less -FRX"
# delta(更好的 diff 显示工具)
git config --global core.pager "delta"

# 文件权限(Windows 上建议关闭)
git config --global core.fileMode false

# 符号链接(Windows 上可能需要关闭)
git config --global core.symlinks true

# 长路径支持(Windows 上重要)
git config --global core.longpaths true

# 文件系统监视(大仓库加速)
git config --global core.fsmonitor true
git config --global core.untrackedcache true

# 默认分支名
git config --global init.defaultBranch main

# 安全目录(多用户环境)
git config --global --add safe.directory '*'

diff 与 merge 工具

bash
# 配置 diff 工具
git config --global diff.tool vscode
git config --global difftool.vscode.cmd 'code --wait --diff $LOCAL $REMOTE'

# 配置 merge 工具
git config --global merge.tool vscode
git config --global mergetool.vscode.cmd 'code --wait --merge $REMOTE $LOCAL $BASE $MERGED'

# 其他常用 diff/merge 工具
# Beyond Compare
git config --global diff.tool bc
git config --global difftool.bc.path "C:/Program Files/Beyond Compare 4/BComp.exe"

# 使用
git difftool              # 用配置的 diff 工具查看差异
git mergetool             # 用配置的 merge 工具解决冲突

# merge 后不保留 .orig 备份文件
git config --global mergetool.keepBackup false

push / pull / fetch 配置

bash
# push 默认行为
git config --global push.default current
# simple   — 推送到同名追踪分支(默认,最安全)
# current  — 推送当前分支到同名远程分支

# 自动设置追踪(Git 2.37+)
git config --global push.autoSetupRemote true

# 自动推送附注标签
git config --global push.followTags true

# pull 默认使用 rebase
git config --global pull.rebase true

# fetch 自动清理过时引用
git config --global fetch.prune true
git config --global fetch.pruneTags true

# 并行获取子模块
git config --global submodule.fetchJobs 4

颜色配置

bash
# 全局启用颜色
git config --global color.ui auto

# 自定义颜色
git config --global color.branch.current "yellow bold"
git config --global color.branch.remote "green"
git config --global color.diff.meta "yellow"
git config --global color.diff.frag "magenta bold"
git config --global color.diff.old "red bold"
git config --global color.diff.new "green bold"
git config --global color.status.added "green"
git config --global color.status.changed "yellow"
git config --global color.status.untracked "red"

Git Alias(命令别名)

基础别名

bash
[alias]
    # 常用缩写
    st = status
    co = checkout
    sw = switch
    br = branch
    ci = commit
    di = diff
    
    # 日志格式
    lg = log --oneline --graph --decorate --all
    ll = log --pretty=format:'%C(yellow)%h%Creset %s %C(green)(%cr)%Creset %C(blue)<%an>%Creset' -20
    
    # 快速操作
    unstage = restore --staged
    discard = restore
    amend = commit --amend --no-edit
    undo = reset --soft HEAD~1
    
    # 分支管理
    branches = branch --sort=-committerdate --format='%(color:green)%(committerdate:relative)%(color:reset) %(color:yellow)%(refname:short)%(color:reset)'
    cleanup = "!git branch --merged main | grep -v 'main\\|develop' | xargs -r git branch -d"

高级别名(Shell 命令)

bash
[alias]
    # 使用 ! 前缀执行 shell 命令
    
    # 查看今天的提交
    today = "!git log --since='00:00:00' --all --oneline --author=\"$(git config user.name)\""
    
    # 查看本周的提交统计
    week = "!git log --since='1 week ago' --all --oneline --author=\"$(git config user.name)\" | wc -l"
    
    # 交互式 add
    ai = add -i
    
    # 查看文件的完整修改历史
    file-history = log --follow -p --
    
    # 查找包含特定文本的提交
    find-text = "!f() { git log --all -S\"$1\" --oneline; }; f"
    
    # 查看两个分支的差异文件列表
    diff-files = "!f() { git diff --name-only $1...$2; }; f"
    
    # 快速创建 fixup 提交
    fixup = "!f() { git commit --fixup=$1; }; f"
    
    # 自动 squash fixup 提交
    autosquash = rebase -i --autosquash
    
    # 统计代码贡献
    contributors = shortlog -sn --all --no-merges
    
    # 查看仓库大小
    repo-size = "!git count-objects -vH | grep size-pack"

别名管理

bash
# 查看所有别名
git config --global --get-regexp alias

# 添加别名
git config --global alias.st status

# 删除别名
git config --global --unset alias.st

# 直接编辑配置文件
git config --global --edit

实际项目中的配置场景

场景 1:新团队成员入职配置

bash
#!/bin/bash
# setup-dev-env.sh — 开发环境一键配置

echo "🔧 Git 开发环境配置"
echo "==================="

# 1. 用户信息
read -p "姓名: " NAME
read -p "邮箱: " EMAIL
git config --global user.name "$NAME"
git config --global user.email "$EMAIL"

# 2. 核心配置
git config --global core.editor "code --wait"
git config --global core.autocrlf true          # Windows
git config --global core.longpaths true
git config --global init.defaultBranch main

# 3. 行为配置
git config --global pull.rebase true
git config --global push.autoSetupRemote true
git config --global push.followTags true
git config --global fetch.prune true
git config --global rerere.enabled true
git config --global merge.conflictStyle zdiff3

# 4. 别名
git config --global alias.st "status"
git config --global alias.sw "switch"
git config --global alias.lg "log --oneline --graph --decorate --all"
git config --global alias.amend "commit --amend --no-edit"
git config --global alias.undo "reset --soft HEAD~1"

# 5. diff 增强(如果安装了 delta)
if command -v delta &> /dev/null; then
    git config --global core.pager "delta"
    git config --global interactive.diffFilter "delta --color-only"
    git config --global delta.navigate true
    git config --global delta.side-by-side true
    echo "✅ delta 已配置"
fi

echo "✅ Git 配置完成!"
echo ""
git config --global --list | head -20

场景 2:配置 delta 美化 diff 输出

bash
# 安装 delta(https://github.com/dandavison/delta)
# Windows: scoop install delta
# macOS: brew install git-delta
# Linux: 下载二进制

# 配置
[core]
    pager = delta

[interactive]
    diffFilter = delta --color-only

[delta]
    navigate = true
    side-by-side = true
    line-numbers = true
    syntax-theme = Dracula

[merge]
    conflictStyle = zdiff3

场景 3:多项目多身份配置

ini
# ~/.gitconfig

[user]
    name = Personal Name
    email = personal@gmail.com

# 公司项目使用工作邮箱
[includeIf "gitdir:C:/Users/admin/work/company-a/"]
    path = C:/Users/admin/.gitconfig-company-a

[includeIf "gitdir:C:/Users/admin/work/company-b/"]
    path = C:/Users/admin/.gitconfig-company-b

# 开源项目使用 GitHub noreply 邮箱
[includeIf "gitdir:C:/Users/admin/opensource/"]
    path = C:/Users/admin/.gitconfig-opensource
ini
# ~/.gitconfig-company-a
[user]
    name = Work Name
    email = name@company-a.com
    signingKey = COMPANY_A_GPG_KEY

[commit]
    gpgSign = true

[core]
    sshCommand = ssh -i ~/.ssh/company_a_key

场景 4:配置 GPG 签名提交

bash
# 1. 生成 GPG 密钥
gpg --full-generate-key

# 2. 获取密钥 ID
gpg --list-secret-keys --keyid-format=long
# sec   rsa4096/ABCDEF1234567890 2026-01-01 [SC]

# 3. 配置 Git 使用 GPG
git config --global user.signingKey ABCDEF1234567890
git config --global commit.gpgSign true
git config --global tag.gpgSign true

# 4. Windows 上可能需要指定 gpg 路径
git config --global gpg.program "C:/Program Files (x86)/GnuPG/bin/gpg.exe"

# 5. 或使用 SSH 签名(更简单,Git 2.34+)
git config --global gpg.format ssh
git config --global user.signingKey ~/.ssh/id_ed25519.pub
git config --global commit.gpgSign true

场景 5:大型仓库性能优化

bash
# 文件系统监视器(显著加速 status/diff)
git config core.fsmonitor true
git config core.untrackedcache true

# 多线程加速
git config pack.threads 0              # 自动使用所有核心
git config checkout.workers 0          # 并行检出

# 稀疏检出(只检出需要的目录)
git sparse-checkout init
git sparse-checkout set src/ docs/

# 部分克隆
git clone --filter=blob:none <url>

# 提交图缓存(加速 log/merge-base)
git config fetch.writeCommitGraph true
git commit-graph write --reachable

# 维护计划
git maintenance register
git maintenance start
# 自动在后台运行 gc、prefetch、commit-graph 等优化

场景 6:安全相关配置

bash
# 禁止 push 到 main
# (通过 hooks 实现,参见 Git hooks 笔记)

# 凭据管理
# Windows
git config --global credential.helper manager-core
# macOS
git config --global credential.helper osxkeychain
# Linux(缓存 1 小时)
git config --global credential.helper 'cache --timeout=3600'

# 防止意外 push 密钥文件(配合 .gitignore)
git config --global core.excludesFile ~/.gitignore_global

# SSH 替代 HTTPS(更安全)
git config --global url."git@github.com:".insteadOf "https://github.com/"

# 禁用 SSL 验证(仅内网使用,不推荐!)
# git config --global http.sslVerify false

配置管理最佳实践

导出和备份配置

bash
# 查看完整配置
git config --global --list

# 导出配置文件
cp ~/.gitconfig ~/dotfiles/.gitconfig

# 使用 dotfiles 仓库管理配置
# 将 .gitconfig 加入 dotfiles 仓库
# 新机器上 symlink 即可

# 快速检查配置
git config --global --list | sort

配置文件模板

ini
# 推荐的 ~/.gitconfig 模板

[user]
    name = Your Name
    email = your@email.com

[core]
    editor = code --wait
    autocrlf = true
    longpaths = true
    pager = delta

[init]
    defaultBranch = main

[pull]
    rebase = true

[push]
    default = current
    autoSetupRemote = true
    followTags = true

[fetch]
    prune = true
    pruneTags = true

[merge]
    conflictStyle = zdiff3

[rerere]
    enabled = true

[diff]
    colorMoved = default

[interactive]
    diffFilter = delta --color-only

[delta]
    navigate = true
    side-by-side = true
    line-numbers = true

[alias]
    st = status
    sw = switch
    br = branch --sort=-committerdate
    lg = log --oneline --graph --decorate --all
    amend = commit --amend --no-edit
    undo = reset --soft HEAD~1
    unstage = restore --staged
    today = "!git log --since='00:00:00' --all --oneline --author=\"$(git config user.name)\""

[credential]
    helper = manager-core

[includeIf "gitdir:C:/Users/admin/work/"]
    path = C:/Users/admin/.gitconfig-work

常见陷阱

陷阱 1:忘记配置用户信息
bash
# 第一次提交时报错
# Please tell me who you are.
# Run git config --global user.email "you@example.com"

# ✅ 安装 Git 后第一件事
git config --global user.name "Your Name"
git config --global user.email "your@email.com"
陷阱 2:Windows 换行符问题
bash
# ❌ 不同 OS 的开发者混用换行符
# Windows: CRLF (\r\n)
# macOS/Linux: LF (\n)
# 导致 diff 中出现大量无意义的变更

# ✅ 配置 autocrlf 或使用 .gitattributes
git config --global core.autocrlf true   # Windows
陷阱 3:全局配置覆盖了仓库配置
bash
# 检查配置优先级
git config --show-origin --show-scope user.email
# local   file:.git/config   work@company.com   ← 优先
# global  file:~/.gitconfig  personal@gmail.com

# 仓库级(--local)始终优先于用户级(--global)
陷阱 4:不安全的凭据存储
bash
# ❌ 明文存储密码
git config --global credential.helper store
# 密码保存在 ~/.git-credentials,任何人可读

# ✅ 使用系统凭据管理器
git config --global credential.helper manager-core   # Windows
git config --global credential.helper osxkeychain    # macOS
陷阱 5:includeIf 路径必须以 / 结尾
bash
# ❌ 不生效
[includeIf "gitdir:~/work"]
    path = ~/.gitconfig-work

# ✅ 路径必须以 / 结尾
[includeIf "gitdir:~/work/"]
    path = ~/.gitconfig-work

常见问题

如何查看某个配置项从哪里来?
bash
git config --show-origin --show-scope user.name
# global  file:C:/Users/admin/.gitconfig  Your Name
如何重置某个配置?
bash
# 删除用户级配置
git config --global --unset user.email

# 删除仓库级配置
git config --local --unset user.email

# 删除整个 section
git config --global --remove-section alias
如何在脚本中使用临时配置?
bash
# 使用环境变量(不影响持久配置)
GIT_AUTHOR_NAME="Bot" GIT_AUTHOR_EMAIL="bot@ci.com" git commit -m "auto commit"

# 或使用 -c 参数
git -c user.name="Bot" -c user.email="bot@ci.com" commit -m "auto commit"
Windows PowerShell 中如何设置编辑器?
powershell
# VS Code
git config --global core.editor "code --wait"

# 路径中有空格时用引号
git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst"
includeIf 支持哪些条件?
ini
# 按目录匹配
[includeIf "gitdir:~/work/"]

# 按目录匹配(大小写不敏感)
[includeIf "gitdir/i:C:/Users/Admin/Work/"]

# 按分支匹配
[includeIf "onbranch:feature/**"]

# 按远程 URL 匹配(Git 2.36+)
[includeIf "hasconfig:remote.*.url:https://github.com/**"]

速查表

目标命令
设置用户名git config --global user.name "Name"
设置邮箱git config --global user.email "e@mail.com"
设置编辑器git config --global core.editor "code --wait"
查看所有配置git config --list
查看配置来源git config --list --show-origin
查看单个配置git config user.name
设置仓库级配置git config --local key value
删除配置git config --global --unset key
编辑全局配置文件git config --global --edit
设置别名git config --global alias.st status
配置默认分支名git config --global init.defaultBranch main
配置 pull rebasegit config --global pull.rebase true
配置自动追踪git config --global push.autoSetupRemote true
配置凭据管理器git config --global credential.helper manager-core

相关命令

参考资料