【发布时间】:2025-12-10 19:55:02
【问题描述】:
我的服务器上有一个名为 test.sh 的脚本:
#!/bin/bash
read -p "Select an option [1-4]: " option
echo "You have selected $option"
当我通过 ssh 手动运行它时,我看到了这个:
me@me:~$ ssh root@server
root@server's password:
[...]
root@server:~# bash test.sh
Select an option [1-4]: 48
You have selected 48
当我将它作为 ssh 远程命令运行时,我看到:
me@me:~$ ssh root@server 'bash test.sh'
root@server's password:
48
You have selected 48
我对此输出不满意,因为它缺少Select an option [1-4]: 提示字符串,而我从test.sh 派生的原始脚本包含很多这样的交互式对话字符串,我需要它们。
我知道read 会将其提示打印到stderr,所以我尝试使用以下命令启动脚本,以防 stderr 被省略,但输出保持不变:
ssh root@server 'bash test.sh >&2'
ssh root@server 'bash test.sh' >&2
ssh root@server 'bash test.sh 2>&1'
ssh root@server 'bash test.sh' 2>&1
为什么会发生这种情况以及如何使 ssh 远程命令按预期工作?
UPD
我已将test.sh 更改为:
#!/bin/bash
echo Connected
read -p "Select an option [1-4]: " option
echo "You have selected $option"
但输出仍然缺少提示字符串:
me@me:~$ ssh root@server 'bash test.sh'
root@server's password:
Connected
66
You have selected 66
【问题讨论】:
-
我已经更新了问题。提示仍然缺失。
-
如果您只想打印该行,则使用
echo打印该行,然后使用read读取值。这是一种解决方法。
标签: linux bash ssh remote-execution