Git command 印出來中文會顯示亂碼
Contents
在 Git Bash、PowerShell 或 CMD 中執行 git log、git diff 時,中文 commit message 可能顯示為亂碼。這個問題的根源在於 Git 的編碼設定與終端機編碼不一致,尤其在 Windows 環境更為明顯。
問題根源
Git 在處理 commit message 時涉及兩個獨立的編碼設定:
i18n.commitEncoding:commit message 儲存時使用的編碼(寫入 Git 物件的編碼)i18n.logOutputEncoding:git log輸出時使用的編碼(終端機顯示的編碼)
如果 commit 是用 UTF-8 儲存,但輸出時終端機是 Big5(Windows CMD 預設),就會看到亂碼。
解決 git log 亂碼
設定 log 輸出編碼
|
|
Windows CMD 環境
CMD 預設使用 Code Page 950(Big5),需先切換到 UTF-8:
|
|
若要每次開啟 CMD 都自動切換,可在 Windows 登錄檔設定,或改用 Windows Terminal。
PowerShell 環境
|
|
加入以下內容到 Profile:
|
|
Git Bash 環境
Git Bash 通常預設 UTF-8,但若仍有問題:
|
|
或使用:
|
|
解決 git status 中文檔名亂碼
這是另一個相關但不同的問題,git status 顯示的中文檔名變成八進位序列:
|
|
不同環境的設定摘要
| 環境 | 主要設定 |
|---|---|
| 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 設定
|
|
git log 常見亂碼排查步驟
- 確認
.gitconfig的i18n.logOutputEncoding = utf-8 - 確認終端機編碼是 UTF-8(CMD 用
chcp 65001,PowerShell 設定 OutputEncoding) - 確認 commit 時使用的編碼(
i18n.commitEncoding)與儲存的一致 - 若使用 pager(less),確認
git config --global core.pager "less -r"支援 UTF-8