Petter Östergren
Petter Östergren

Reputation: 1013

BASH: ssh access variable result on remote host

How do I make a variable accessible on a remote computer via ssh?

I have a bash array containing n IP addresses for this specific instance I want to send the "result" of the first element in the array to the remote machine for further use.

#!/bin/bash
servers=(192.168.130.252 10.10.10.10 12.12.12.12)


echo "Before ssh: ${servers[0]}"
ssh ubuntu@"${servers[0]}" /bin/bash<<"EOF"
    echo "$(hostname -I | awk '{print $1}')"
    echo "After ssh: ${servers[0]}"
    # MORE COMMAND HERE
EOF
exit 0

#Output
Before ssh: 192.168.130.252
192.168.130.252
After ssh:  

Upvotes: 0

Views: 162

Answers (1)

Philippe
Philippe

Reputation: 26767

Because you have used quotes in "EOF", ${servers[0]} gets expanded in remote shell, so to an empty string as array servers is not defined. One way around is :

#!/bin/bash
servers=(192.168.130.252 10.10.10.10 12.12.12.12)

echo "Before ssh: ${servers[0]}"
ssh ubuntu@"${servers[0]}" CURRENT_HOST="${servers[0]}" /bin/bash<<"EOF"
    echo "$(hostname -I | awk '{print $1}')"
    echo "After ssh: $CURRENT_HOST"
    # MORE COMMAND HERE
EOF
exit 0

Just found a way to send the whole array to remote shell:

#!/bin/bash
servers=(192.168.130.252 10.10.10.10 12.12.12.12)

echo "Before ssh: ${servers[0]}"
{ declare -p servers
  cat << "EOF"
    echo "$(hostname -I | awk '{print $1}')"
    echo "After ssh: ${servers[0]}"
    # MORE COMMAND HERE
EOF
} | ssh ubuntu@"${servers[0]}" /bin/bash

Upvotes: 2

Related Questions