How to use an array with remote variable on remote

2019-09-18 23:13发布

问题:

This is what I am trying to do...

#!/bin/bash

array_local=(1 2 3 4 5)

ssh user@server << EOF
index_remote=1
echo \$index_remote
echo \${array_local[\$index_remote]}  
EOF

When I try to run the above script I get the O/P as 1 and a null value (blank space). I wanted ${array_local[$index_remote} value to be 2 instead of null, I need to access this local array using remote variable for my further work in the script..

回答1:

<<EOF results variable expansion happening on the local machine, but you only defined the variable i on the remote machine. You need to think carefully about where you want to do the expansion. You haven't explained in your question whether the value of i is defined client-side or server-side, but I'm guessing from your subsequent comments that you want it done server-side. In that case you'll need to pass the array contents over ssh, which requires careful quoting:

ssh hostname@server <<EOF
i=1
eval `typeset -p array_local`
echo \${array_local[\$i]}
EOF

typeset -p array_local will output the string

declare -a array_local='([0]="1" [1]="2" [2]="3" [3]="4" [4]="5")'

Since this is inside backticks, it will get expanded client-side within the EOF-delimited heredoc, and then evaluated server-side by the eval. In other words it's equivalent to:

ssh hostname@server <<'EOF'
i=1
declare -a array_local='([0]="1" [1]="2" [2]="3" [3]="4" [4]="5")'
echo ${array_local[$i]}
EOF

Notice the difference in EOF quoting between the two examples. The first one allows parameter and shell expansion, and the second doesn't. That's why the echo line in the first one needs quoting, to ensure that parameter expansion happens server-side not client-side.