我在 bash 中举这个简单的例子:
echo a "b c" d
正确的输出是:
a b c d
它在内部“编码”为三个参数的数组,而中间的一个(包含b
和c
)为 4 个字符长并包含 2 个空格。这是set -x
在 bash 中启用时的调试输出(不是破折号)
echo a "b c" d
+ echo a 'b c' d
a b c d
现在, ssh 命令似乎完全忽略了这一点,并且似乎在内部将其连接到一个不正确的字符串,否则我无法解释结果:
$ ssh user@remotehost -- echo a "b c" d
+ ssh user@remotehost -- echo a 'b c' d
a b c d
$ ssh user@remotehost echo a "b c" d
+ ssh user@remotehost echo a 'b c' d
a b c d
$ ssh user@remotehost 'echo a "b c" d'
+ ssh user@remotehost 'echo a "b c" d'
a b c d
正如您所看到的,最后一行效果最好,但如果字符串变得更复杂,我就会遇到问题,例如:
$ text="doesn't work"
+ text='doesn'\''t work'
$ echo "$text"
+ echo 'doesn'\''t work'
doesn't work
$ ssh user@remotehost echo "$text"
+ ssh user@remotehost echo 'doesn'\''t work'
bash: -c: line 0: unexpected EOF while looking for matching `''
bash: -c: line 1: syntax error: unexpected end of file
$ ssh user@remotehost "echo $text"
+ ssh user@remotehost 'echo doesn'\''t work'
bash: -c: line 0: unexpected EOF while looking for matching `''
bash: -c: line 1: syntax error: unexpected end of file
$ ssh user@remotehost "echo \'$text\'"
+ ssh user@remotehost 'echo \'\''doesn'\''t work\'\'''
'doesnt work\
$ ssh user@remotehost "echo '$text'"
+ ssh user@remotehost 'echo '\''doesn'\''t work'\'''
bash: -c: line 0: unexpected EOF while looking for matching `''
bash: -c: line 1: syntax error: unexpected end of file
问题是:我在那里任何执行远程命令并以最佳实践方式传递变量的方法("$variable"
多个参数),这样我就不必关心它的内容,或者其内容是否危险?
同样的限制似乎也适用于sh -c
可能是问题根源的情况,其他命令做得更好(它们直接调用二进制文件而不是使用 shell):
$ sudo -- echo a 'b c' d
[sudo] password for user:
a b c d
$ nohup echo a 'b c' d
nohup: ignoring input and appending output to 'nohup.out'
$ cat nohup.out
a b c d