Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays ssh bash-s遇到数组变量错误_Arrays_Linux_Bash_Ssh - Fatal编程技术网

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

Arrays ssh bash-s遇到数组变量错误,arrays,linux,bash,ssh,Arrays,Linux,Bash,Ssh,以下脚本引发错误: 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 我需要转义$x变量,因为我使用了“bash-s”远程s

以下脚本引发错误:

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
我需要转义$x变量,因为我使用了“bash-s”远程shell。当我删除反斜杠时,我只访问本地变量,而不是执行脚本的服务器上的变量

有人知道访问数组内容的解决方案吗?

您可以引用终止符声明,以避免必须转义输入字符串中的任何内容(当然,这也意味着您不能在远程脚本中插入局部变量的值):

此外,您还可以通过以下几种方式简化命令:

  • 在运行远程命令时,不应该指定
    bash-s
    ,除非这与默认shell不同
  • export
    ing在后续脚本调用中不使用的变量是没有意义的
  • 当您立即分配数组文字时,不需要
    声明-a

谢谢您的回答。但是我需要将局部变量的值注入远程脚本。有没有办法做到这两个方面?
./q.sh: line 6: $x: syntax error: operand expected (error token is "$x")
my_command << 'EOF'
foo $bar
[...]
EOF
my_input='some $literal$ strings'
my_input="${my_input}${my_variable}"
[...]