I am trying to run an ssh command in my shell script which will automatically create a database, user, password etc on a remote server:
password=`date +%s|sha256sum|base64|head -c 32`
read -p "Enter staging folder name... e.g. xxxxxxxx: " stagingdirectory
echo $stagingdirectory
read -p "Give the name for the database (this will be used in mysql)" dbname
echo $dbname
read -p "Give the name of the user for the database (this will be used in mysql)" dbuser
echo $dbuser
sqlstatement="mysql -uXXXXXXX -pXXXXXXXX -hXXXXXXXX -e "
sqlstatement+='"CREATE DATABASE IF NOT EXISTS $dbname;CREATE USER $dbuser@'%' IDENTIFIED BY '$password';GRANT ALL PRIVILEGES ON $dbname.* TO $dbuser@'%';FLUSH PRIVILEGES;"'
echo $sqlstatement
ssh -A [email protected] -e "$sqlstatement"
When I try and run this command, I get this error:
This is what gets returned (I have replaced actual values with XXXX):
Bad escape character 'mysql -udbadmin -pXXXXX -hXXXXX -e"CREATE DATABASE IF NOT EXISTS $dbname;CREATE USER $dbuser@% IDENTIFIED BY XXXXXX;GRANT ALL PRIVILEGES ON $dbname.* TO $dbuser@%;FLUSH PRIVILEGES;"'.
I think this is due to my sql statement and strings escaping.
$(echo $sqlstatement), the problem is in there.