【发布时间】:2020-05-28 23:10:34
【问题描述】:
在 node 中执行 bash 命令并传递动态参数时,标准方法是使用 spawn 并避免转义。那就是:
const filename = 'file with spaces'
spawn('ls', [filename]) // All good, received 'file with spaces'
这是万无一失的,因为文件名作为独立变量传递给 bash。
现在,如果我想通过 ssh 做同样的事情会发生什么?以下是不是选项:
const filename = 'file with spaces'
spawn('ssh', [host, 'ls', filename]) // Wrong!! Received 'file' 'with' 'spaces'
Ssh 接受 ls 和 filename 作为 vargars。加入它并执行,这违背了目的。
【问题讨论】:
-
我认为您可能需要转义单引号,例如
filename = '\'file with spaces\'' -
不,那不好。这在很大程度上取决于输入,这是动态的
-
传递单个字符串(适当构造)是您唯一真正的选择;
ssh只是将它的参数天真地加入一个字符串中,以便在远程主机上与$SHELL -c一起使用。 -
创建一个函数
quote_me(string),在输入中加上单引号并尝试spawn('ssh', [host, 'ls', quote_me(filename)])。 -
@WalterA 转义字符非常棘手,而且总有一些情况下它不起作用。例如,在您的情况下,文件名可能在名称中包含引号