Linux 終端亂碼是初學者最大挫折來源。本文從**編碼設定、字體支援、終端模擬器配置**三大維度,提供系統性排查與永久解決方案。
| 類型 | 現象 | 核心成因 | 典型場景 |
|---|---|---|---|
| 中文亂碼 | 中文顯示為 □、亂碼、亂碼 | Locale 未設定、終端編碼與系統編碼不匹配、缺少中文字體 | 新安裝 Linux、SSH 連線、Docker 容器 |
| 英文/符號亂碼 | ls、cat 顯示亂碼、提示符變形 | 輸出二進制檔案 (含控制字元) 污染終端狀態 | cat 二進制檔、編譯輸出、core dump |
| 偽終端亂碼 | SSH 連線中 cat 二進制檔後終端完全失控 | 控制字元改變終端模式 (如切換字符集、啟用繪圖字符集) | SSH 遠程操作、screen/tmux 會話 |
locale
# 輸出範例:
LANG=zh_CN.UTF-8
LC_CTYPE="zh_CN.UTF-8"
LC_ALL=
# 方法 A: 修改用戶級配置 (~/.bashrc 或 ~/.profile)
echo 'export LANG=zh_CN.UTF-8' >> ~/.bashrc
echo 'export LC_ALL=zh_CN.UTF-8' >> ~/.bashrc
source ~/.bashrc
# 方法 B: 系統級 (需 root)
# /etc/locale.conf (systemd) 或 /etc/default/locale (Debian/Ubuntu)
echo 'LANG=zh_CN.UTF-8' > /etc/locale.conf
# 方法 C: 生成 Locale (若缺失)
locale-gen zh_CN.UTF-8 # Debian/Ubuntu
# 或 localedef -i zh_CN -f UTF-8 zh_CN.UTF-8 (通用)
編輯 → 設定 → 編碼 選 UTF-8Window → Translation → Remote character set: UTF-8# Ubuntu/Debian
sudo apt install fonts-wqy-zenhei fonts-wqy-microhei fonts-noto-cjk
# CentOS/RHEL/Fedora
sudo dnf install wqy-zenhei-fonts wqy-microhei-fonts google-noto-sans-cjk-fonts
# Arch/Manjaro
sudo pacman -S wqy-zenhei wqy-microhei noto-fonts-cjk
誤 cat 二進制檔導致終端進入異常狀態 (如啟用繪圖字符集 G1)。
reset
# 或
stty sane
echo -e '\033c' # ESC c: 硬重置 (VT100 指令)
reset 會重新初始化終端、清空緩衝區、恢復預設模式,通常 1-2 秒完成。
當 reset 失效 (如 SSH 會話中控制字元破壞協商狀態),使用 tput 發送終端能力序列:
tput sgr0 # 重置所有屬性 (顏色、粗體、底線、反轉...)
tput reset # 完整重置 (等同 reset 命令)
tput init # 初始化終端 (輸出 terminfo 定義的初始化字串)
# 針對性恢復
tput rmcup # 退出替代畫面緩衝區 (screen/vi/less 退出時自動執行)
tput cnorm # 顯示游標
tput clear # 清屏
oracle@linux-suse:~> cat fibo.pyc
# 輸出大量控制字元,提示符變成 VT102VT102...
oracle@linux-suse:~> tput sgr0
# 終端恢復正常提示符
oracle@linux-suse:~>
# Oracle 客戶端環境變數 (設置於 ~/.bashrc 或 /etc/profile)
export NLS_LANG=SIMPLIFIED CHINESE_CHINA.ZHS16GBK # 連接 GBK 資料庫
# 或
export NLS_LANG=SIMPLIFIED CHINESE_CHINA.AL32UTF8 # 連接 UTF-8 資料庫 (推薦)
# 確保終端 Locale 與 NLS_LANG 字元集一致
export LANG=zh_CN.UTF-8
export LC_ALL=zh_CN.UTF-8
# Dockerfile FROM ubuntu:22.04 ENV LANG=zh_CN.UTF-8 \ LC_ALL=zh_CN.UTF-8 \ DEBIAN_FRONTEND=noninteractive RUN apt-get update && apt-get install -y \ locales fonts-wqy-zenhei fonts-wqy-microhei && \ locale-gen zh_CN.UTF-8 && \ apt-get clean && rm -rf /var/lib/apt/lists/*
locale → 確認 LANG=zh_CN.UTF-8echo $TERM → 確認 xterm-256color 或 linuxcat /etc/locale.gen | grep zh_CN → 確認 Locale 已生成fc-list :lang=zh → 確認已安裝中文字體Linux 終端亂碼 90% 由 **Locale/編碼不匹配** 或 **二進制輸出污染終端狀態** 引起。遵循「系統 Locale=UTF-8、終端編碼=UTF-8、安裝中文字體、誤輸出二進制即 reset/tput sgr0」四步驟,可永久告別亂碼困擾。