For the following code:
array1=( "Germany" "Vietnam" "Argentina" )
array2=( "Europe" "Asia" "America" )
sshpass -p $IPA_PASS ssh -tt -o StrictHostKeyChecking=no $IPA_NAME@$TARGET "sudo su - jboss <<'EOF'
for i in "${!array1[@]}"
do
echo \$i
echo \${array1[\$i]} "is in" \${array2[\$i]}
done
EOF
"
I want the output:
0
Germany is in Europe
1
Vietnam is in Asia
2
Argentia is in America
But I get:
0
Germany is in Europe
1
Germany is in Europe
2
Germany is in Europe
So the index is printed correctly but the value taken from the array over SSH is always the first element. How can this be respectively the first, second, and third element?
The for-loop works fine when not passed over SSH in EOF statements, but the script needs to be run over SSH.
CodePudding user response:
Here is a working example with bash for local testing. You can exchange the two bash commands by ssh / sudo:
bash -c "bash <<EOF
array1=( \"Germany\" \"Vietnam\" \"Argentina\" )
array2=( \"Europe\" \"Asia\" \"America\" )
for i in \\\${!array1[@]}
do
echo \\\$i
echo \\\${array1[\\\$i]} is in \\\${array2[\\\$i]}
done
EOF
"
You also might think about transferring a working script to your remote machine and execute it there in order to escape the quoting-madness.
CodePudding user response:
You can transfer the definitions of two arrays using declare -p
:
array1=( "Germany" "Vietnam" "Argentina" )
array2=( "Europe" "Asia" "America" )
sshpass -p $IPA_PASS ssh -o StrictHostKeyChecking=no $IPA_NAME@$TARGET sudo -u jboss bash\
< <(declare -p array1 array2; cat <<'EOF'
for i in "${!array1[@]}"
do
echo $i
echo ${array1[i]} "is in" ${array2[i]}
done
EOF
)