在 CentOS 上使用 nohup 运行程序时日志出现中文乱码,通常不是 nohup 本身的问题,而是字符编码不一致导致的。下面从原因到解决办法系统说明。
CentOS 默认应使用 zh_CN.UTF-8 或 en_US.UTF-8,但如果环境变量不对,程序输出就会乱码。
检查当前字符集:
locale
正常应类似:
LANG=zh_CN.UTF-8
LC_ALL=zh_CN.UTF-8
如果是:
LANG=C
或
zh_CN.GBK
就很可能乱码。
nohup command > log.out 2>&1 &
如果当前 shell 的 LANG 不对,日志就会按错误编码写入。
-Dfile.encoding=UTF-8PYTHONIOENCODING)setlocale比如:
cat + 错误终端# 查看支持的语言
locale -a | grep UTF-8
# 设置环境变量
export LANG=zh_CN.UTF-8
export LC_ALL=zh_CN.UTF-8
写入永久生效:
echo 'export LANG=zh_CN.UTF-8' >> ~/.bashrc
echo 'export LC_ALL=zh_CN.UTF-8' >> ~/.bashrc
source ~/.bashrc
然后重新运行:
nohup your_command > log.out 2>&1 &
nohup java -Dfile.encoding=UTF-8 -jar app.jar > log.out 2>&1 &
Python 示例:
nohup env PYTHONIOENCODING=utf-8 python app.py > log.out 2>&1 &
iconv 转换已有日志(补救)如果日志已经乱码:
iconv -f GBK -t UTF-8 log.out > log_utf8.out
less:less -r log.out
locale 是 UTF-8export LANGCentOS 上 nohup 日志中文乱码,99% 是因为 LANG / LC_ALL 不是 UTF-8,或程序未指定 UTF-8 编码。
如果你愿意,可以告诉我:
locale 输出我可以帮你精准定位。