mysqlbashunixterminalspecial-characters

How to run MySQL command on bash?


The following code works on the command line

mysql --user='myusername' --password='mypassword' --database='mydatabase' --execute='DROP DATABASE myusername; 
CREATE DATABASE mydatabase;'

However, it doesn't work on bash file on execution

#!/bin/bash
user=myusername
password=mypassword
database=mydatabase

mysql --user='$user' --password='$password' --database='$database' --execute='DROP DATABASE $user; CREATE DATABASE $database;'

I receive the following error:

ERROR 1045 (28000): Access denied for user '$user'@'localhost' (using password: YES)

How to make the bash file run as the command line?


Solution

  • To get variables expanded in bash, use double quotes (i.e. "), cf. SC2016, for example:

    mysql \
      --user="$user" \
      --password="$password" \
      --database="$database" \
      --execute="DROP DATABASE $user; CREATE DATABASE $database;"