Contents

Git command 印出來中文會顯示亂碼

在 Git Bash、PowerShell 或 CMD 中執行 git loggit diff 時,中文 commit message 可能顯示為亂碼。這個問題的根源在於 Git 的編碼設定與終端機編碼不一致,尤其在 Windows 環境更為明顯。

問題根源

Git 在處理 commit message 時涉及兩個獨立的編碼設定:

  • i18n.commitEncoding:commit message 儲存時使用的編碼(寫入 Git 物件的編碼)
  • i18n.logOutputEncodinggit log 輸出時使用的編碼(終端機顯示的編碼)

如果 commit 是用 UTF-8 儲存,但輸出時終端機是 Big5(Windows CMD 預設),就會看到亂碼。

解決 git log 亂碼

設定 log 輸出編碼

1
2
3
4
5
# 讓 git log 輸出 UTF-8
git config --global i18n.logOutputEncoding utf-8

# 確保 commit 以 UTF-8 儲存
git config --global i18n.commitEncoding utf-8

Windows CMD 環境

CMD 預設使用 Code Page 950(Big5),需先切換到 UTF-8:

1
2
3
4
5
rem 切換到 UTF-8 Code Page
chcp 65001

rem 之後執行 git log 就能正確顯示中文
git log --oneline

若要每次開啟 CMD 都自動切換,可在 Windows 登錄檔設定,或改用 Windows Terminal。

PowerShell 環境

1
2
3
4
5
# 在 PowerShell 中設定 UTF-8 輸出
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# 也可加入 $PROFILE,每次啟動自動執行
notepad $PROFILE

加入以下內容到 Profile:

1
2
3
$OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8

Git Bash 環境

Git Bash 通常預設 UTF-8,但若仍有問題:

1
2
3
# 在 ~/.bashrc 或 ~/.bash_profile 加入
export LANG=zh_TW.UTF-8
export LC_ALL=zh_TW.UTF-8

或使用:

1
export LC_ALL=C.UTF-8

解決 git status 中文檔名亂碼

這是另一個相關但不同的問題,git status 顯示的中文檔名變成八進位序列:

1
2
# 關閉 quotepath,讓中文檔名正常顯示
git config --global core.quotepath false

不同環境的設定摘要

環境 主要設定
CMD chcp 65001 切換 Code Page
PowerShell [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
Git Bash export LC_ALL=C.UTF-8
所有環境(Git 設定) git config --global i18n.logOutputEncoding utf-8

完整 .gitconfig 設定

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

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

[log]
    date = iso

git log 常見亂碼排查步驟

  1. 確認 .gitconfigi18n.logOutputEncoding = utf-8
  2. 確認終端機編碼是 UTF-8(CMD 用 chcp 65001,PowerShell 設定 OutputEncoding)
  3. 確認 commit 時使用的編碼(i18n.commitEncoding)與儲存的一致
  4. 若使用 pager(less),確認 git config --global core.pager "less -r" 支援 UTF-8

參考資料