在 Windows 系统上,PowerShell 默认使用 GB2312/GBK 编码,而 GitHub 使用 UTF-8 编码。当 commit message 包含中文时,如果 Git 没有正确配置编码,会导致在 GitHub 上显示为乱码。
# 设置 commit message 编码为 UTF-8
git config --global i18n.commitencoding utf-8
# 设置 log 输出编码为 UTF-8
git config --global i18n.logoutputencoding utf-8
# 禁用路径引用(避免中文路径显示为转义序列)
git config --global core.quotepath false在 PowerShell 中执行:
# 设置控制台输出编码为 UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
# 或者添加到 PowerShell 配置文件(永久生效)
# 编辑 $PROFILE 文件,添加:
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8# 检查 Git 编码配置
git config --global --get i18n.commitencoding
git config --global --get i18n.logoutputencoding
git config --global --get core.quotepath
# 应该输出:
# utf-8
# utf-8
# false如果已经提交了乱码的 commit message,可以使用以下方法修复:
git commit --amend -m "新的正确的中文 commit message"
git push --force # 注意:如果已经 push 到远程,需要使用 force push# 修改最近 3 个 commit
git rebase -i HEAD~3
# 在编辑器中,将要修改的 commit 前的 "pick" 改为 "reword"
# 保存后,Git 会逐个提示修改 commit message对于大量 commit 需要修改的情况,可以使用 git filter-branch,但操作复杂,建议谨慎使用。
- 使用 UTF-8 编码的编辑器:确保你的代码编辑器(如 VS Code)使用 UTF-8 编码保存文件
- 设置 Git 编辑器编码:如果使用自定义编辑器,确保编辑器也使用 UTF-8
- 检查 .gitattributes:可以在项目中添加
.gitattributes文件,指定文件编码:
*.txt text encoding=utf-8
*.md text encoding=utf-8
*.c text encoding=utf-8
*.h text encoding=utf-8
- 修改已 push 的 commit message 需要使用
--forcepush,这会影响其他协作者 - 如果是团队项目,修改 commit message 前应该与团队沟通
- 建议在项目开始时就配置好编码设置,避免后续问题