我正在尝试运行以下 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}\'
。
如何正确地转义这些单引号?
更新
根据@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
答案1
您不需要使用\
双引号:
$ DB_USER='abc'; echo "test '${DB_USER}'"
test 'abc'
或者,您可以断开双引号,并转义单引号 - 这是必要的地方:
$ DB_USER='abc'; echo "test"\'"${DB_USER}"\'
test'abc'
另一种方法是使用printf
命令替换并使用引号的十六进制值(\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})"
附注:脚本中有 3 条命令调用sudo
。这是多余的。只需以 方式运行整个脚本,sudo myscript.sh
无需sudo
在每行中添加内容。