Contents

Git 中文顯示亂碼

在 Windows 的 CMD 或 PowerShell 中使用 Git 指令時,中文檔案名稱常常顯示為奇怪的八進位跳脫序列(如 \344\270\255\346\226\207)。本文說明亂碼的原因與各種解決方式。

亂碼的原因

core.quotepath 問題(檔案名稱亂碼)

Git 預設開啟 core.quotepath,這個設定會對路徑中的非 ASCII 字符(包含中文)以八進位跳脫序列(octal escape)表示:

1
2
3
4
5
# 亂碼顯示
\344\270\255\346\226\207\346\AA\264\366\220\23.md

# 正常顯示應為
中文檔案.md

解決方式:關閉 core.quotepath

1
git config --global core.quotepath false

設定後,git statusgit add 等指令顯示的中文檔名就會正常。

git log 中文亂碼(CMD 環境)

在 CMD 中執行 git log 看到中文 commit message 亂碼,是因為 CMD 預設使用 Big5(CP950)編碼,而 Git 輸出是 UTF-8:

1
2
3
4
5
# CMD 中臨時切換到 UTF-8
set LC_ALL=C.UTF-8

# Windows 10 永久設定(系統環境變數)
setx LC_ALL C.UTF-8

gitk 圖形介面中文亂碼

1
git config --global gui.encoding utf-8

i18n 相關設定

Git 的 i18n 設定控制 commit message 的編碼處理:

1
2
3
4
5
# commit message 儲存的編碼(建議 UTF-8)
git config --global i18n.commitEncoding utf-8

# git log 輸出 commit message 時使用的編碼
git config --global i18n.logOutputEncoding utf-8

大多數情況下,只要確保 commitEncodinglogOutputEncoding 都是 UTF-8,就不會有問題。

Windows Terminal 的設定

Windows Terminal 預設使用 UTF-8,通常不需要額外設定。若仍有問題,確認:

  1. 在 Windows Terminal 的設定中,確認字型支援中文(如「微軟正黑體」或「Noto Sans CJK」)
  2. 在 PowerShell Profile 中加入:
1
2
3
# $PROFILE 中加入
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8

CMD 中的字符集設定

1
2
rem 切換 CMD 到 UTF-8
chcp 65001

chcp 65001 將 CMD 的 Code Page 切換為 UTF-8,之後 Git 的中文輸出就能正確顯示。可以在 ~/.gitconfig 或 Git Bash 的設定中加入 alias 自動執行。

完整的 .gitconfig 建議設定

1
2
3
4
5
6
7
8
9
[core]
    quotepath = false

[i18n]
    commitEncoding = utf-8
    logOutputEncoding = utf-8

[gui]
    encoding = utf-8

參考資料