Search code examples
bashpts

bash invoked via ssh does not store variables


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


Solution

  • 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'