Git中文社区

初次配置(可选)

安装好 Git 后,第一件事是配置你的个人信息。Git 使用 git config 命令读取和设置配置变量,这些配置决定了 Git 的外观和行为。

配置文件的三个级别

Git 的配置保存在三个不同的位置,优先级从低到高:

级别参数位置作用范围
系统级--systemGit 安装目录下的 etc/gitconfig系统上所有用户
全局级--global~/.gitconfig当前用户的所有仓库
仓库级--local(默认)仓库内的 .git/config仅当前仓库

每一个级别都会覆盖上一级别的同名配置。比如,你可以在全局设置个人邮箱,在公司项目里单独设置公司邮箱。

设置用户信息

每一次 Git 提交都会使用用户名和邮箱,这些信息会被永久写入提交记录:

git config --global user.name "张三"
git config --global user.email "[email protected]"

如果某个项目需要使用不同的身份,在项目目录中去掉 --global 重新设置即可:

cd my-company-project
git config user.email "[email protected]"

提示

如果要把代码推送到 GitHub 或 Gitee,建议邮箱与平台账号绑定的邮箱一致,这样提交记录才能正确关联到你的账号。

设置默认分支名

新版 Git 允许自定义 git init 创建的初始分支名。目前主流平台都使用 main:

git config --global init.defaultBranch main

设置默认编辑器

当 Git 需要你输入信息(例如编写提交说明)时,会调用默认编辑器。默认一般是 Vim,如果你更习惯 VS Code:

git config --global core.editor "code --wait"

换行符设置

Windows 使用 CRLF(\r\n)作为换行符,而 macOS 和 Linux 使用 LF(\n)。跨平台协作时,换行符不一致会导致整个文件都显示为"被修改"。

# Windows:提交时转换为 LF,检出时转换为 CRLF
git config --global core.autocrlf true

# macOS / Linux:提交时转换为 LF,检出时不转换
git config --global core.autocrlf input

更可靠的做法是在仓库中添加 .gitattributes 文件统一规则:

* text=auto eol=lf
*.bat text eol=crlf
*.png binary

解决中文文件名乱码

默认情况下,git status 会把中文文件名显示成 \346\265\213\350\257\225.txt 这样的八进制转义。关闭这个行为即可正常显示:

git config --global core.quotepath false

在 Windows 的 Git Bash 中如果仍有乱码,可以额外设置:

git config --global gui.encoding utf-8
git config --global i18n.commitEncoding utf-8
git config --global i18n.logOutputEncoding utf-8

设置命令别名

别名可以让常用命令更短:

git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.lg "log --oneline --graph --decorate --all"

之后就可以用 git st 代替 git status,用 git lg 查看漂亮的分支图。

配置代理

如果你需要连接远程仓库,如 GitHub 等国外平台。由于网络环境的影响,代码拉取速度会比较慢,此时你需要配置 HTTP 代理。

如何配置请查看代理设置教程,或使用我们的代理设置向导工具。

查看配置

# 列出所有配置
git config --list

# 同时显示配置来自哪个文件
git config --list --show-origin

# 查看某一项
git config user.name

获取帮助

Git 的任何命令都有详细的帮助文档:

git help config
git config --help

# 简洁版帮助
git config -h