Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 547
johnatasjmo Avatar asked Nov 17 '13 17:11

johnatasjmo


People also ask

How do I run a SQL command in bash?

Execute SQL query from the Linux command-lineThe password that is used to connect to SQL Database. Name of the Database that we need to connect. Name of the host where the Database is Installed. It is used to print results using a tab as the column separator, with each row on a new line.


1 Answers

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.

like image 59
anubhava Avatar answered Sep 21 '22 10:09

anubhava