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?

0

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

4 Comments

tried that out !! no luck !!
@Silent_Rebel Where is /home/ubuntu/temp.txt file located? Local or remote?
its there on the remote server..
I think that was the tweak.. It is working now .. thanks..
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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.