【问题标题】:Capture output of bash script over ssh within script在脚本中通过 ssh 捕获 bash 脚本的输出
【发布时间】:2018-03-02 01:42:56
【问题描述】:

我知道这个讨论: Running A Bash Script Over SSH

然而,我对此有一些不同的看法——这让我很困惑。

我的 ~/.ssh/config 中有一个名为 remServer 的 ssh 别名,我可以通过 ssh 访问它。我想在该服务器上运行一些远程命令并处理本地服务器上的输出。

我的问题在于将变量替换为 ssh 命令(这样一个基本主题),但我在这里遗漏了一些东西。

问题来了:

#this works
op="ls"
cmd="ssh remServer '$op'"
res=`$cmd`
echo $res

#this doesn't
op="ls -lt"
cmd="ssh remServer '$op'"
res=`$cmd`
echo $res

无论我使用单引号或双引号有多少种方式,我只能得到以下内容:

找不到bash ls -lt 命令

【问题讨论】:

  • 以交互方式运行ssh remServer 'ls' 会发生什么?您能否检查远程系统上的 shell 配置文件(.bashrc 等),看看是否有 ls 命令的别名?
  • 您好!感谢您的观看。以交互方式运行,我得到一个简单的文件列表(如预期的那样) - 就像我在远程服务器本身上所做的一样(所以没有改变那里的 ls 命令)。

标签: bash ssh


【解决方案1】:

由于您传入文字单引号,因此执行的命令将变为 'ls -lt',这在本地也会产生相同的错误(与不带引号的 ls -lt 相反)。

最简单的解决方案就是去掉引号:

op="ls -lt"
cmd="ssh remServer $op"
res=`$cmd`
echo $res

更好的解决方案是使用正确的数组和转义:

op=(ls -lt)
cmd=(ssh remServer "$(printf '%q ' "${op[@]}")" )
res=$("${cmd[@]}")
echo "$res"

【讨论】: