0

I'm trying to send a bash command over SSH using ssh -q $REMOTE -x "command". Because I have multiple bash commands, I'm using << EOF.

The problem is that the readlink command returns me an empty string when I assign its result to a variable. When I call it directly, it's not.

Here is a simplified version of my code :

ssh -q $REMOTE -x << EOF
    LINK="/path/to/my/link" # the link points to /path/to/my/file
    readlink $LINK # outputs /path/to/my/file
    TEST=$(readlink -f "$LINK")
    echo $TEST # outputs an empty string
EOF

At that point I put the same code in a shell script on the remote machine and tried to call the shell script :

# local machine
ssh -q $REMOTE -x << EOF
    ./test-script
EOF
# remote machine "test-script"
LINK="/path/to/my/link" # the link points to /path/to/my/file
readlink $LINK # outputs /path/to/my/file
TEST=$(readlink -f "$LINK")
echo $TEST # outputs /path/to/my/file

Suddently it's working, when I'm calling the remote script everything works fine, but why is it not working over ssh ?

1

2 Answers 2

3

Within the here document, your variables are being evaluated on the source side. If you want to have your variables be evaluated on the target side, escape the $. For example,

ssh -q $REMOTE -x << EOF
    LINK="/path/to/my/link"
    readlink \$LINK
    TEST=\$(readlink -f "\$LINK")
    echo \$TEST
EOF

Hope this helps

1
  • After a long time searching for the right solution someone finally came up with something very straightforward an not using weird tricks. I'll remember \$ forever.
    – Mike
    Apr 30, 2019 at 14:18
0

From Bash Reference Manual:

The format of here-documents is:

[n]<<[-]word
        here-document
delimiter

If any part of word is quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence \newline is ignored, and \ must be used to quote the characters \, $, and `.

So either escape $ (like this other answer says) or use << "EOF" (with quotes); otherwise syntax like $variable and $(…) will be resolved locally.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .