运行 通过 ssh 的程序失败 "Error opening terminal: unknown."

running a program through ssh fails with "Error opening terminal: unknown."

当我尝试通过ssh 执行一个简单的命令时,它成功了。例如

#] ssh servername "echo abcd"
abcd
#] 

但是,当我尝试以下命令时,它失败了:

#] ssh servername  ~/htopmem.sh
Error opening terminal: unknown.
#] 

其中htopmem.sh的内容在下方。 (灵感来自 Marwan Alsabbagh 在 htop output to human readable file 上的回答)

#!/bin/bash
echo q | htop | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g" | ~/aha --black --line-fix | grep Mem | grep -E -o "[0-9]+/[0-9]+"

如果我手动ssh到服务器和运行 htopmem,那么执行成功:

#] ./htopmem.sh
6515/24021
#] 

知道如何使 "ssh servername ~/htopmem.sh" 命令起作用吗?

谢谢!

像这样的普通 ssh 命令没有 tty(终端)。使用 -t 选项强制 ssh 打开终端。

来自manual

-t

Force pseudo-tty allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g., when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty.

所以这会工作(更好):

ssh -t servername  ~/htopmem.sh