mysqldatabasebashshellterminal

how do i add database name with hyphen character using script in ubuntu


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

hyph=`ls -l $DBDIR | egrep '^d' | grep '.-.' | awk '{print $9}'`

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

Solution

  • In mysql queries table names may contain alphanumeric characters, underscore and dollar sign. In order to be able to use other ANSI characters you must place names in single backquotes.

    `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

    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.

    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'`;'