bash invoked via ssh does not store variables

123 views Asked by At

there is a problem with the invoked via ssh bash, although i have read mans about it i still can't explain the following:

Here is a script, very simple

#!/bin/bash
theUser=$1
theHost=$2
ssh -tt $theUser@$theHost 'bash' << EOF
a=1
echo 'dat '$a
exit
EOF

and here is the result:

victor@moria:~$ bash thelast.sh victor 10.0.0.8
[email protected]'s password:
a=1
echo 'dat '
exit
victor@mordor:~$ a=1
victor@mordor:~$ echo 'dat '
dat
victor@mordor:~$ exit
exit
Connection to 10.0.0.8 closed.

As you may see, the environment doesn't store the value of the variable "a" so it can't echo it, but any other commands like ls or date return the result.

So the question is what i am doing wrong and how to avoid such behavior?

p.s. i can't replace ssh -tt, but any other command may be freely replaced.

Thanks in advance

2

There are 2 answers

0
AudioBubble On BEST ANSWER

Inside the here document, the $a is expanded locally before feeding the input to the ssh command. You can prevent that by quoting the terminator after the << operator as in

ssh -tt $theUser@$theHost 'bash' << 'EOF'
0
Tom Fenech On

$a is being expanded in the local shell, where it is undefined. In order to prevent this from happening, you should escape it:

echo "dat \$a"

Escaping the $ causes it to be passed literally to the remote shell, rather than being interpreted as an expansion locally. I have also added some double quotes, as it is good practice to enclose parameter expansions inside them.