Passing comma separated variable to remote SSH Session

Rahul

I am trying to read comma separated variable in shell script and splitting it like as below

while [ -z "$variable" ]
do      printf 'variable: '
        read -r variable
        [ -z "$variable" ] && echo 'Action number cannot be empty; try again.'
done

for i in $(echo ${variable} | sed "s/,/ /g")
do
    echo "$i"
done

It gives be output as below

abc
def

But if i am trying same thing with SSH its not working i am trying as below

while [ -z "$variable" ]
do      printf 'variable: '
        read -r variable
        [ -z "$variable" ] && echo 'Action number cannot be empty; try again.'
done

ssh -i my.pem -p 2022 ec2-user@ip-address 'bash -s' << EOF

sudo su - << SUEOF

echo "input $variable"

for i in $(echo ${variable} | sed "s/,/ /g")
do
    echo "$i"
done
SUEOF
EOF

But in SSH its not printing the values of input variable i am using echo to check the variable is passing into SSH session and i can see the variable is passing to SSH session

variable: abc,def
input abc,def


Please help me solving the issue

Inian

It is because the $variable expansion inside the ssh heredoc, is expanded by the local shell on the local machine rather than in the remote shell. Generally, we escape the expansion sequences i.e. variable expansion $var as \$var and command substitutions as \$(..) instead of $(..), if we expect the expansion to happen in the remote shell.

So in your for loop, the split on , happens with your sed command but your "$i" expansion will again happen in the local shell which should have been happening in the remote shell. Due to lack of appropriate escape sequences, the echo "$i" will never see a value in the local shell.

You can get around by marking $i as \$i so that, its expansion happens remotely. Also the loop for i in $(echo $variable | sed sed "s/,/ /g") is an extremely fragile way to iterate over a list split on de-limiter ,. Use the shell built-ins, read in this case

ssh -i my.pem -p 2022 ec2-user@ip-address 'bash -s' <<EOF
echo "input $variable"
IFS="," read -ra split <<<"$variable"
for var in "\${split[@]}"; do
    printf '%s\n' "\$var"
done
EOF

Note the usage of escape sequences around the array expansion, "\${split[@]}" and the variable "\$var" which ensures the expansion of those variables happen remotely and not in the local machine.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related