现象
日常工作通过Mac自带Terminal远程ssh到linux服务器完成,制表符显示总是不正常,例如htop运行效果如下图
而用PC的gitbash正常ssh的显示是这样的
可以看出command列中正常的制表符└─
变成了`--
原因
通常乱码问题是语言环境变量错误,通过locale命令将有关当前语言环境或全部公共语言环境的信息写到标准输出上。
问题终端结果:
$ locale
locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_ALL to default locale: No such file or directory
LANG=C.UTF-8
LANGUAGE=
LC_CTYPE=UTF-8
LC_NUMERIC="C.UTF-8"
LC_TIME="C.UTF-8"
LC_COLLATE="C.UTF-8"
LC_MONETARY="C.UTF-8"
LC_MESSAGES="C.UTF-8"
LC_PAPER="C.UTF-8"
LC_NAME="C.UTF-8"
LC_ADDRESS="C.UTF-8"
LC_TELEPHONE="C.UTF-8"
LC_MEASUREMENT="C.UTF-8"
LC_IDENTIFICATION="C.UTF-8"
LC_ALL=
正常终端结果:
$ locale
LANG=C.UTF-8
LANGUAGE=
LC_CTYPE="C.UTF-8"
LC_NUMERIC="C.UTF-8"
LC_TIME="C.UTF-8"
LC_COLLATE="C.UTF-8"
LC_MONETARY="C.UTF-8"
LC_MESSAGES="C.UTF-8"
LC_PAPER="C.UTF-8"
LC_NAME="C.UTF-8"
LC_ADDRESS="C.UTF-8"
LC_TELEPHONE="C.UTF-8"
LC_MEASUREMENT="C.UTF-8"
LC_IDENTIFICATION="C.UTF-8"
LC_ALL=
问题出在LC_CTYPE上,问题终端值为UTF-8无法被系统识别
而新版macOS换用zsh为默认终端后不再包含LC_CTYPE变量
调用bash后进一步证实猜想
zsh% echo $LC_CYTPE
zsh% bash
The default interactive shell is now zsh.
To update your account to use zsh, please run `chsh -s /bin/zsh`.
For more details, please visit https://support.apple.com/kb/HT208050.
bash-3.2$ echo $LC_CTYPE
UTF-8
Mac在连接ssh时默认会将部分环境变量转发,其中包含LANG和LC_*
而转发的UTF-8无法被Linux正确识别,从而导致编码错误。
解决
明白了原因,给出两种解决方案
方案一:添加本地变量
建立~/.zshrc
写入环境变量
export LC_CTYPE="C.UTF-8"
重启终端或source后连接正常。
方案二:禁用变量转发
编辑ssh配置文件
sudo vi /etc/ssh/ssh_config
找到并注释如下行
SendEnv LANG LC_*
禁止发送语言相关环境变量,重新连接后正常。