The question is how to substitute local and remote variables in a Remote SSH session.
I have a script on local Server. And following is the extract from it.
#!/bin/bash
Date=`/bin/date`
Schedule="2016-02-01 14:30:00"
Startup_loop()
{
#ssh connection to remote host $1 and start of loop of statements to be executed remotely
ssh root@$1 << EOF
#To display the Remote Hostname
hostname
#Check if the following local variables are available remotely as well
echo $Date
echo $Schedule
#Check and set the variable sysconf_clock_var on remote host
clock_var=`/usr/bin/grep BLAH /etc/Command | /usr/bin/awk -F\" '{ print $2}'`
echo $clock_var
#Modify the proc based on $startup_schedule
echo $clock_var >> /proc/Schedule
#Change the paramter on the remote file /etc/Command
sed -i -e 's/BLAH="yes"/BLAH="no"/' /etc/Command
echo "The remote ssh is completed" >> /tmp/File_$Schedule_$Date.log
EOF
}
#Main Loop
##Accept the system IP from the User
echo Hello Please enter the system IP
read systemIP
#Call the procedure by passing the system IP
Startup_loop $systemIP
The script does not function as expected. E.g the value of hostname command inside ssh loop shows local hostname. What is failing here?
Consider the following pattern:
This works because quoting the sigil used for a heredoc (
<<'EOF'
, not<<EOF
) prevents any expansions from taking place locally, such that they're all remote; then, usingenv
to put these quoted values in the remote environment before the shell interpreter starts ensures that they're available for use.At the same time,
printf %q
formats content in such a way that a remote shell executing it will only see the exact values, making variables with values such asvar1=$'$(rm -rf *)\'$(rm -rf *)\''
safe.When I run the code given (with the only modification being the value of
rmthost
), the output is as follows: