How to run mysql command on bash?

johnatasjmo picture johnatasjmo · Nov 17, 2013 · Viewed 114.1k times · Source

The following code works on the command line

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

However, it doesnt work on bash file on excecution

#!/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?

Answer

anubhava picture anubhava · Nov 17, 2013

Use double quotes while using BASH variables.

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

BASH doesn't expand variables in single quotes.