本文针对的问题是“Ubuntu 安装中文语言包”“Ubuntu Server中文问题”,“Ubuntu更改语言环境”,“Ubuntu locale的设定”,“cannot change locale (zh_CN.UTF-8)”,“Linux中文乱码”,“Linux字符集的修改”,“Linux乱码的解决办法”等问题,提供一站式解决。如果系统显示中文异常,例如出现显示中文乱码等,可以参考本文章。关于CentOS系统的修改办法,请参考文章末尾的描述。
问题描述
终端显示中文正常,应用程序里面显示中文异常。
错误表现
1
$ sudo dpkg-reconfigure locales
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
LANGUAGE = "zh_CN:zh:en_US:en",
LC_ALL = "zh_CN.UTF-8",
LANG = "zh_CN.UTF-8"
are supported and installed on your system.
perl: warning: Falling back to the standard locale ("C").
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_MESSAGES to default locale: No such file or directory
locale: Cannot set LC_ALL to default locale: No such file or directory
/bin/bash: warning: setlocale: LC_ALL: cannot change locale (zh_CN.UTF-8)
Generating locales...
en_US.UTF-8... /usr/sbin/locale-gen: line 177: warning: setlocale: LC_ALL: cannot change locale (zh_CN.UTF-8)
up-to-date
Generation complete.
1
$ man locale
man: can't set the locale; make sure $LC_* and $LANG are correct
1
$ locale
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_MESSAGES to default locale: No such file or directory
locale: Cannot set LC_ALL to default locale: No such file or directory
LANG=zh_CN.UTF-8
LANGUAGE=zh_CN:zh:en_US:en
LC_CTYPE="zh_CN.UTF-8"
LC_NUMERIC="zh_CN.UTF-8"
LC_TIME="zh_CN.UTF-8"
LC_COLLATE="zh_CN.UTF-8"
LC_MONETARY="zh_CN.UTF-8"
LC_MESSAGES="zh_CN.UTF-8"
LC_PAPER="zh_CN.UTF-8"
LC_NAME="zh_CN.UTF-8"
LC_ADDRESS="zh_CN.UTF-8"
LC_TELEPHONE="zh_CN.UTF-8"
LC_MEASUREMENT="zh_CN.UTF-8"
LC_IDENTIFICATION="zh_CN.UTF-8"
LC_ALL=
1
$ localectl list-locales
C.UTF-8
en_US.utf8
zh_CN.utf8
问题解决办法
要想达到应用程序中正常显示中文字符的目的,要下面的三个变量应该如下,
1 2 3
LANG=zh_CN.UTF-8 LANGUAGE=zh_CN:zh:en_US:en LC_ALL=LC_ALL=zh_CN.UTF-8
但问题在于“LC_ALL to default locale: No such file or directory”和“LC_ALL: cannot change locale (zh_CN.UTF-8) ”,因此重新安装中文语言包。
执行下面命令
1
sudo apt-get -y install language-pack-zh-hans
或
1
sudo apt-get -y install language-pack-zh-hans language-pack-zh-hans-base
如果想支持繁体字,则执行
1
sudo apt-get -y install language-pack-zh-hant
或
1
sudo apt-get -y install language-pack-zh-hant language-pack-zh-hant-base
再执行locale命令设置当前locale环境
1
locale
相关的文件和参考
相关手册:man locale(1), locale(5), locale(7)
相关文件:/usr/share/i18n/SUPPORTED
相关命令:
locale --all-locales 列出当前系统中所有支持的locale
localectl list-locales 列出当前系统中所有可用的locale
localectl set-locales LOCALE... 修改当前系统中的locale,与locale功能相同,与export上文提到的三个变量相同
对于CentOS,可以直接编辑/etc/sysconfig/i18n文件,将LANG="en_US.UTF-8"设置成LANG="zh_CN.UTF-8",除此之外,CentOS下locale命令的显示结果如下:
1
# locale