How to run MySQL command on bash?

MysqlBashUnixTerminalSpecial Characters

Mysql Problem Overview


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?

Mysql Solutions


Solution 1 - Mysql

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.

Solution 2 - Mysql

This one worked, double quotes when $user and $password are outside single quotes. Single quotes when inside a single quote statement.

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

Solution 3 - Mysql

I have written a shell script which will read data from properties file and then run mysql script on shell script. sharing this may help to others.

#!/bin/bash
    PROPERTY_FILE=filename.properties

    function getProperty {
       PROP_KEY=$1
       PROP_VALUE=`cat $PROPERTY_FILE | grep "$PROP_KEY" | cut -d'=' -f2`
       echo $PROP_VALUE
    }

    echo "# Reading property from $PROPERTY_FILE"
    DB_USER=$(getProperty "db.username")
    DB_PASS=$(getProperty "db.password")
    ROOT_LOC=$(getProperty "root.location")
    echo $DB_USER
    echo $DB_PASS
    echo $ROOT_LOC
    echo "Writing on DB ... "
    mysql -u$DB_USER -p$DB_PASS dbname<<EOFMYSQL

    update tablename set tablename.value_ = "$ROOT_LOC" where tablename.name_="Root directory location";
    EOFMYSQL
    echo "Writing root location($ROOT_LOC) is done ... "
    counter=`mysql -u${DB_USER} -p${DB_PASS} dbname -e "select count(*) from tablename where tablename.name_='Root directory location' and tablename.value_ = '$ROOT_LOC';" | grep -v "count"`;

    if [ "$counter" = "1" ]
    then
    echo "ROOT location updated"
    fi

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjohnatasjmoView Question on Stackoverflow
Solution 1 - MysqlanubhavaView Answer on Stackoverflow
Solution 2 - MysqljohnatasjmoView Answer on Stackoverflow
Solution 3 - MysqlflopcoderView Answer on Stackoverflow