I am trying to run the follow bash code:
#!/bin/bash
export DEBIAN_FRONTEND=noninteractive
DB_USER='abc'
DB_USER_PASSWORD='123'
DB_MAGENTO='db_magento'
sudo apt-get update
echo debconf mysql-server/root_password password $DB_USER_PASSWORD | sudo debconf-set-selections
echo debconf mysql-server/root_password_again password $DB_USER_PASSWORD | sudo debconf-set-selections
sudo apt-get -qq install mysql-server > /dev/null # Install MySQL quietly
sudo mysql -uroot -p123 -e "CREATE SCHEMA ${DB_MAGENTO} DEFAULT CHARACTER SET utf8;SHOW DATABASES;CREATE USER \'${DB_USER}\'@'localhost' IDENTIFIED BY ${DB_USER_PASSWORD};GRANT ALL PRIVILEGES ON * . * TO \'${DB_USER}\'@'localhost'; FLUSH PRIVILEGES;SELECT Host,User,Password FROM mysql.user;"The error I am getting is ERROR at line 1: Unknown command '\''.Seems to be related with \'${DB_USER}\' .
How to escape these single quotes properly?
UPDATE
Afetr @Sergiy suggestion I am getting another error:
#!/bin/bash
export DEBIAN_FRONTEND=noninteractive
DB_USER='ila'
DB_USER_PASSWORD='123'
DB_MAGENTO='db_magento' mysql -uroot -p123 -e "SHOW DATABASES;CREATE USER '${DB_USER}'@'localhost' IDENTIFIED BY ${DB_USER_PASSWORD};GRANT ALL PRIVILEGES ON * . * TO '${DB_USER}'@'localhost'; FLUSH PRIVILEGES;SELECT Host,User,Password FROM mysql.user;"Error:
$ sudo ./installMagento.sh
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database |
+--------------------+
| information_schema |
| db_magento |
| mysql |
| performance_schema |
| sys |
+--------------------+
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '123' at line 1 1 Answer
You should not need to use \ with double quotes:
$ DB_USER='abc'; echo "test '${DB_USER}'"
test 'abc'Alternatively, you can break the double quote, and escape the single quote - that's where it's necessary:
$ DB_USER='abc'; echo "test"\'"${DB_USER}"\'
test'abc'Yet another way would be to use printf with command substitution and using hex value for the quote (\x27):
sudo mysql -uroot -p123 -e "$(printf 'CREATE SCHEMA \x27%s\x27 DEFAULT CHARACTER SET utf8;SHOW DATABASES;CREATE USER \x27%s\x27@\x27localhost\x27 IDENTIFIED BY %s ; GRANT ALL PRIVILEGES ON * . * TO \x27%s\x27@'localhost'; FLUSH PRIVILEGES;SELECT Host,User,Password FROM mysql.user;' ${DB_MAGENTO} ${DB_USER} ${DB_USER_PASSWORD} ${DB_USER})"Side note: you have 3 commands in the script calling sudo. This is redundant. Just run the whole script as sudo myscript.sh and remove the need to add sudo to each of those lines.