# 查看当前Locale设置
locale
# 安装中文语言包(以Ubuntu为例)
sudo apt-get install language-pack-zh-hans
# 设置系统Locale为中文UTF-8
sudo update-locale LANG=zh_CN.UTF-8
sudo update-locale LC_ALL=zh_CN.UTF-8
# 立即生效(或重新登录)
source /etc/default/locale
确保终端使用UTF-8编码:
# 临时设置(仅当前会话有效)
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
# 或中文环境
export LANG=zh_CN.UTF-8
export LC_ALL=zh_CN.UTF-8
对于PuTTY等SSH客户端: - 在连接设置中将字符集改为UTF-8 - 关闭"调整字符集以适应终端窗口"选项
如果文件本身编码有问题:
# 检查文件编码
file -i filename
# 转换编码(例如GBK转UTF-8)
iconv -f GBK -t UTF-8 input.txt -o output.txt
# 批量转换(例如将当前目录下所有.txt文件转为UTF-8)
find . -name "*.txt" -exec iconv -f GBK -t UTF-8 {} -o {}.utf8 \;
VIM中显示乱码:
" 在~/.vimrc中添加
set encoding=utf-8
set fileencodings=ucs-bom,utf-8,cp936,gb18030,big5,euc-jp,euc-kr,latin1
MySQL客户端乱码:
mysql -u root -p --default-character-set=utf8
将以下内容添加到~/.bashrc
或~/.bash_profile
中:
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
export LANGUAGE=en_US.UTF-8
然后执行:
source ~/.bashrc
# 查看系统支持的locale
locale -a
# 查看当前终端编码
echo $LANG
# 测试UTF-8支持
echo -e '\xe4\xb8\xad\xe6\x96\x87' # 应该显示"中文"
通过以上方法,大多数Linux命令行乱码问题都能得到解决。如果问题仍然存在,可能需要检查特定的应用程序配置或考虑更换终端模拟器。