Reputation: 1125
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.
Upvotes: 0
Views: 551
Reputation: 1309
Try changing the line,
ssh -A [email protected] -e "$sqlstatement"
to
ssh -A [email protected] "$sqlstatement"
From the manual of ssh, see below
-e escape_char
Sets the escape character for sessions with a pty (default: ‘~’). The escape character is only recognized at the beginning of a line. The escape character followed by a dot (‘.’) closes the connection; followed by control-Z suspends the connection; and followed by itself sends the escape char- acter once. Setting the character to “none” disables any escapes and makes the session fully transparent.
Here in your example, ssh is not getting a valid escape character, and you don't need one either
Upvotes: 2