简体   繁体   中英

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:

./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. 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.
  • There's no point in export ing variables which are not used in subsequent script calls
  • You don't need to declare -a when you assign an array literal immediately

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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