简体   繁体   English

ssh bash -s遇到数组变量错误

[英]ssh bash -s meets array variable error

The following script throws an error: 以下脚本将引发错误:

declare -a service_ports=(22 80 443 445)

ssh root@host 'bash -s' << EOF

export x=0
while [ \$x -le "${#service_ports[@]}" ]
do
  echo Port ${service_ports[\$x]} # ERROR HERE
  x=\$(( \$x + 1 ))
done

EOF

When I run this bash script I get: 当我运行这个bash脚本时,我得到:

./q.sh: line 6: $x: syntax error: operand expected (error token is "$x")

I need to escape the $x variable because I use a " bash -s " remote shell. 我需要转义$ x变量,因为我使用了“ bash -s ”远程shell。 When I remove the backslash I only access my local variable and not the one on the server where the script is executed. 当我删除反斜杠时,我只访问我的本地变量,而不是执行脚本的服务器上的变量。

Anyone know the solution to access the content of the array? 有人知道访问阵列内容的解决方案吗?

You can quote the here document terminator declaration to avoid having to escape anything in the input string (of course that also means you can't inject the value of a local variable in the remote script): 您可以引用此文档终止符声明,以避免必须转义输入字符串中的任何内容 (当然这也意味着您不能在远程脚本中注入局部变量的值):

my_command << 'EOF'
foo $bar
[...]
EOF

If you need to inject local variable contents, you could instead go for mixed quotes: 如果你需要注入局部变量内容,你可以改为使用混合引号:

my_input='some $literal$ strings'
my_input="${my_input}${my_variable}"
[...]

Also, you can simplify your command in several ways: 此外,您可以通过以下几种方式简化命令:

  • You shouldn't have to specify bash -s when running a remote command, unless that is different from your default shell. 除非与默认shell不同,否则在运行远程命令时不必指定bash -s
  • There's no point in export ing variables which are not used in subsequent script calls export变量没有意义,这些变量未在后续脚本调用中使用
  • You don't need to declare -a when you assign an array literal immediately 当您立即分配数组文字时,不需要declare -a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM