我正在尝试运行以下 bash 代码:
#!/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;"
我得到的错误ERROR at line 1: Unknown command '\''.
似乎与\'${DB_USER}\'
.
如何正确转义这些单引号?
更新
Afetr @Sergiy 建议我收到另一个错误:
#!/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;"
错误:
$ 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
您不需要使用
\
双引号:或者,您可以打破双引号,并转义单引号 - 这就是必要的地方:
另一种方法是使用
printf
命令替换并为引号 (\x27
) 使用十六进制值:旁注:脚本调用中有 3 个命令
sudo
。这是多余的。只需运行整个脚本sudo myscript.sh
并删除添加sudo
到每一行的需要。