1

How can I pass an array across the ssh connection.

I have an array formed thus:

declare -a target_array=(
    "item1 -p12345 -r"
    "item2 -p65677 -e"
)

I then need to pass it to an ssh connection as follows:

ssh $server target_array=${target_array[@]}" "bash -s" <<TARGETSCRIPT
    echo "hello"
TARGETSCRIPT

But this just gives me the error:

bash: -p12345: command not found

What is the best way to do this? I've tried with and without {}, with and without [@] but nothing seems to work.

(n.b. that echo hello is just a placeholder for an 800 line script that makes use of the target_array).

0

You can't put the array as the first argument to ssh behind the host. It will be evaluated as the command and obviously fails. If you really need to do this, you should add it into the "script" like this:

ssh $server "bash -s" <<TARGETSCRIPT
    target_array=("${target_array[@]}")
    echo ${target_array[@]}
    echo "hello"
TARGETSCRIPT

Also encapsulating the array properly is useful to make sure the array stays the same on the other end.

  • 1
    Those ${target_array[@]} are expanded by the local shell. Also what if elements contain things like $(rm -rf ~)? – Stéphane Chazelas Jan 25 '16 at 17:44
2
remote_code=$(cat << 'EOF'
echo Hello
for i in "${!target_array[@]}"; do
  echo "$i -> ${target_array[i]}"
done
EOF
)

ssh server bash << EOF
$(declare -p target_array)
$remote_code
EOF

The remote shell will see on stdin something like:

declare -a target_array='([0]="item1 -p12345 -r" [1]="item2 -p65677 -e")'
echo Hello
for i in "${!target_array[@]}"; do
  echo "$i -> ${target_array[i]}"
done

To avoid clobbering the remote shell's stdin, and assuming your ssh and the remote sshd allows passing LC_* environment variables, you could also do:

LC_CODE="$(declare -p target_array)
$remote_code" ssh server 'bash -c '\''eval "$LC_CODE"'\'

If you know the login shell of the remote user is bash, you can simply do:

ssh server "$(declare -p target_array)
$remote_code"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.