1

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?

Will
  • 24,082
  • 14
  • 97
  • 108
Silent_Rebel
  • 300
  • 4
  • 15

3 Answers3

1

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
heemayl
  • 39,294
  • 7
  • 70
  • 76
1

You should be able to simply do this:

ssh -i $KEYFILE_PATH ubuntu@$TARGET_INSTANCE_IP "bash"  <<'_END_'
    cat /home/ubuntu/temp.txt
    string=$(cat /home/ubuntu/temp.txt)
    echo $string
_END_

<<'_END_' ... _END_ is called a Here Document literal, or "heredoc" literal. The single quotes around '_END_' prevent the local shell from interpreting variables and commands inside the heredoc.

Will
  • 24,082
  • 14
  • 97
  • 108
0

The intermediate shell is not required (assuming you use bash on the remote system). Also you dont have to use an intermediate HERE-DOC. Just pass a multiline Command:

ssh -i $KEYFILE_PATH ubuntu@$TARGET_INSTANCE_IP '

cat /home/ubuntu/temp.txt
string=$(cat /home/ubuntu/temp.txt )
echo $string
'

Note I am using single quotes to prevent evaluation on the local shell.

Jürgen Hötzel
  • 18,997
  • 3
  • 42
  • 58