bash 我如何在 ubuntu 中使用脚本添加带有连字符的数据库名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35592034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how do i add database name with hyphen character using script in ubuntu
提问by 1312EN
I've tried using this code in a script but it just created what is inside the backtick. In this example, "echo "table-db"" was created in the database. It didn't create the name of the folder with the hyphen character in the query
我曾尝试在脚本中使用此代码,但它只是创建了反引号内的内容。在此示例中,在数据库中创建了“echo "table-db"”。它没有在查询中使用连字符创建文件夹的名称
hyph=`ls -l $DBDIR | egrep '^d' | grep '.-.' | awk '{print }'`
dbhype=($hyph)
for dbtry in ${!dbhype[*]}
do
mysql -u$dbUser -p$dbPass -e 'CREATE DATABASE IF NOT EXISTS `echo "table-db"` CHARACTER SET utf8 COLLATE utf8_general_ci';
echo "Database ${dbhype[$dbtry]} created."
done
回答by user2683246
In mysql queries table names may containalphanumeric characters, underscore and dollar sign. In order to be able to use other ANSI characters you must place names in single backquotes.
在 mysql 查询表名中可能包含字母数字字符、下划线和美元符号。为了能够使用其他 ANSI 字符,您必须将名称放在单个反引号中。
`table-db`
But in bash they have different meaning and used for command substitution. In bash there are also several types of strings -- in double quotes and in single quotes. The difference between them is that in double quotes variable expansion and command substitution are performed, while in single quotes they don't. So you can use backquotes with mysql semantics within single quotes as is
但是在 bash 中,它们具有不同的含义并用于命令替换。在 bash 中还有几种类型的字符串——双引号和单引号。它们之间的区别在于,在双引号中执行变量扩展和命令替换,而在单引号中则不执行。因此,您可以按原样在单引号内使用带有 mysql 语义的反引号
mysql -e 'CREATE DATABASE `table-db`;'
but must escape them when using within double quotes, so that they wouldn't be interpreted by bash as command sustitution.
但在双引号内使用时必须将它们转义,以便 bash 不会将它们解释为命令替代。
mysql -e "CREATE DATABASE \`table-db\`;"
As you want to get the database name from variable you need to place it beyond single quote strings, like that:
当您想从变量中获取数据库名称时,您需要将其放在单引号字符串之外,如下所示:
mysql -e "CREATE DATABASE \`$dbname\`;"
or like that:
或者像这样:
mysql -e 'CREATE DATABASE `'$dbname'`;'