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
You should not need to use
\
with double quotes:Alternatively, you can break the double quote, and escape the single quote - that's where it's necessary:
Yet another way would be to use
printf
with command substitution and using hex value for the quote (\x27
):Side note: you have 3 commands in the script calling
sudo
. This is redundant. Just run the whole script assudo myscript.sh
and remove the need to addsudo
to each of those lines.