Mysql – bash: use outside variables when reading multiple lines into ssh

bashMySQL

I apologize if the title doesn't quite describe what I'm looking for. Please edit if possible.

I have a bash script that does the following:

serveruser="root"
serverip=1.2.3.4
serverpath="/var/www"


ssh "$serveruser"@"$serverip" /bin/bash <<\EOF
mkdir -p "$serverpath/mysqldumps/"
cd "$serverpath/mysqldumps/"
domainname=somedomain.com
mysqldump -h 192.168.1.4 -udba -ppassword -c --add-drop-table --add-locks --create-options --databases --quick --lock-tables $domainname > $domainname.sql
EOF

My problem is that the multiple lines I am "feeding" to ssh don't parse the variables I set before. This is obviously because the variables aren't set on the remote machine, only in my local shell. How could I pass these variables or possibly pass multiple lines to ssh in a different way?

Best Answer

The way you're escaping the here-doc word is preventing variable substitution. Contrast

cat <<\END
$PATH
$LOGNAME
END

versus

cat <<END
$PATH
$LOGNAME
END

update

On closer inspection, I see you're setting a variable in the heredoc. That should not be expanded on the local machine, so you need to escape those in the mysqldump command. Try this:

ssh "$serveruser"@"$serverip" <<EOF
mkdir -p "$serverpath/mysqldumps/"
cd "$serverpath/mysqldumps/"
domainname=somedomain.com
mysqldump -h 192.168.1.4 -udba -ppassword -c --add-drop-table --add-locks --create-options --databases --quick --lock-tables \$domainname > \$domainname.sql
EOF