Git 的用户配置 ~/.gitconfig

摘要

为什么有这个文件

姓名、邮箱、编辑器、拉取方式这些选项,每个仓库都可以单独放一份。放在 ~/.gitconfig 里之后,这个用户新建或克隆的仓库都会带上,不用每个目录再设一遍。

文件在用户主目录,不在仓库里,git clone 不会把它带走,也不会提交进历史。改它只影响这台机器上、这个用户以后执行的 Git 命令。已经生成的提交不会因此改写。

几份配置谁生效

Git 每次执行都会重新读配置文件,没有单独的进程需要重载。后读到的同名键覆盖先读到的。

范围 写入选项 文件 管哪些仓库
system --system $(prefix)/etc/gitconfig 这台机器上的所有用户
global --global ~/.config/git/config,然后是 ~/.gitconfig 当前用户的所有仓库
local 在仓库里执行,不加范围 .git/config 只这个仓库
单次 git -c 键=值 不写文件 只这一条命令

$XDG_CONFIG_HOME 有值时,用它代替 ~/.config。两份全局文件都存在时都会读,~/.gitconfig 里的同名键盖过 ~/.config/git/config。仓库里的 .git/config 再盖过全局。

--global 默认写 ~/.gitconfig。只有 ~/.gitconfig 还不存在、并且 ~/.config/git/config 已经存在时,才会改写后者。

git -c user.email=临时@example.com commit 只影响这一次,文件内容不动。环境变量 GIT_AUTHOR_EMAIL、GIT_COMMITTER_EMAIL 也只影响当前这次提交的作者或提交者,不写入 ~/.gitconfig。

创建和修改

还没有这个文件时,第一条 --global 会创建它。

1
2
git config --global user.name "你的名字"
git config --global user.email "you@example.com"

用编辑器打开同一份文件。保存后,下一条 git 命令就会读到新内容。

1
2
3
# 不带 -m 的 git commit 也会打开这里设的编辑器
git config --global core.editor "vim"
git config --global --edit

也可以直接编辑 ~/.gitconfig。它是隐藏文件,ls -a ~ 才能看见。语法和 .git/config 相同:方括号是节,节里面是键和值。# 开头的是注释。

1
2
3
4
5
[user]
name = 你的名字
email = you@example.com
[core]
editor = vim

只想改当前这个仓库时,在仓库目录里执行,不加 --global。值写入该仓库的 .git/config,并盖过 ~/.gitconfig 里的同名键。

1
2
git config user.name "这个仓库用的名字"
git config user.email "repo@example.com"

同一个键在文件里出现了多行时,普通的设置命令会报错。--replace-all 把这些行全部换成新值。

1
git config --global --replace-all user.email "you@example.com"

删掉某一个键,文件还在:

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

整份全局配置先停用时,把文件改名。仓库自己的 .git/config 不受影响。

1
mv ~/.gitconfig ~/.gitconfig.bak

常用项

键 作用
user.name 以后新提交的作者名
user.email 以后新提交的作者邮箱。GitHub 用它对应账号
core.editor git commit、git rebase -i 打开的编辑器
init.defaultBranch git init 时的默认分支名。设为 main 后,新仓库的第一分支叫 main
pull.rebase true 时,git pull 用变基接上远程分支,不再产生合并提交
push.autoSetupRemote true 时,新分支第一次 git push 会自动建立上游跟踪,不用再写 -u。Git 2.37 起可用
core.excludesfile 所有仓库共用的忽略文件,见 Git安装和常用命令(最新) 的「.gitignore」一节
credential.helper HTTPS 密码交给哪个助手。助手的配置见 Git 的 HTTPS 凭据和 SSH 密钥

pull.rebase true 写进 ~/.gitconfig 之后,这个用户的每个仓库,以后的 git pull 都改走变基。已经存在的合并提交不会被改写。

密码和令牌不要写进这个文件。credential.helper 只记录用哪一个助手,口令在钥匙串或助手自己的存储里。

签名用的 gpg.format、user.signingkey、commit.gpgsign 也放在这里,步骤见 用 SSH 密钥签名 Git 提交。

别名

alias 节把一条短命令展开成后面的 Git 命令。下面这条让 git st 等于 git status。

1
git config --global alias.st status

文件里对应:

1
2
[alias]
st = status

按目录再引入一份

个人姓名和邮箱留在 ~/.gitconfig。某个目录树要用另一套时,在文件末尾用 includeIf 引入第二份文件。公司仓库放在 ~/work/ 下的写法见 同一台电脑使用两个 GitHub 账号。

确认读到的是哪一份

在仓库目录里执行。输出左边是文件路径,右边是生效的值。全局里有邮箱、这个仓库的 .git/config 里也有时,这里显示的是仓库那一份。

1
git config --show-origin --get user.email

只看某个键最终生效的值,或者只看全局文件里写了什么:

1
2
3
4
git config user.name

# 只读 ~/.gitconfig 和 ~/.config/git/config
git config --global --list

要看每一层实际写了什么,不只看最终生效的那条:

1
2
# --show-scope 标出 system、global、local
git config --list --show-origin --show-scope

git config --global --get user.email 能打出全局值,只说明 ~/.gitconfig 里有这一行。当前仓库用的是不是它,要看上面带 --show-origin 的那条。