我有一个 bash 脚本可以自动安装 Nextcloud 服务器。
要运行 MySQL 命令,我使用 mysql -e 命令
user@hostname:~$ mysql -e "CREATE DATABASE ‘NextcloudDataBaseName’"
我想将数据库名称、用户名、密码等存储在变量中
如何编写带有变量的 mysql -e 命令?
user@hostname:~$ mysql -e "CREATE USER ‘$UserName’@'localhost' IDENTIFIED BY ‘$UserPass’"
user@hostname:~$ mysql -e "CREATE USER ${UserName}@'localhost' IDENTIFIED BY ${UserPass}"
上面两个命令不运行
用户密码(测试密码)错误消息:
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'qwerty1234'
这种语法似乎有效:
user@hostname:~$ mysql -e "CREATE USER '${DbUserName}'@'localhost' IDENTIFIED BY '${DbUserPass}'"
变量名周围的简单引号但这是最佳语法,最佳实践吗?
谢谢 :-)
答案1
像这样(此处文档):
mysql<<EOF
CREATE USER '$UserName'@'localhost' IDENTIFIED BY '$UserPass';
EOF
学习如何在 shell 中正确引用,这非常重要:
“双引号”每个包含空格/元字符的文字和每一个扩展:
"$var"
,"$(command "$var")"
,"${array[@]}"
,"a & b"
。用于'single quotes'
代码或文字$'s: 'Costs $5 US'
,ssh host 'echo "$HOSTNAME"'
。请参阅
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
http://wiki.bash-hackers.org/syntax/words