Silent_Rebel Silent_Rebel - 5 months ago 12
Bash Question

Assigning variables inside remote shell script execution over SSH

I am trying to execute some shell script on a remote server via SSH.

Given below is a code sample:

ssh -i $KEYFILE_PATH ubuntu@$TARGET_INSTANCE_IP "bash" << EOF
#!/bin/bash
cat /home/ubuntu/temp.txt
string=$(cat /home/ubuntu/temp.txt )
echo $string
EOF


cat prints the expected result but
$string
prints nothing.

How do I store the return value of
cat
in a variable?

Answer

You need to make the content of Here doc literal otherwise they will be expanded in the current shell, not in the desired remote shell.

Quote EOF:

ssh .... <<'EOF'
...
...
EOF