如何在 bash 上运行 MySQL 命令?

下面的代码在命令行上运行

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

但是,它在执行时不能在 bash 文件上工作

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


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

我收到以下错误:

错误1045(28000) : 拒绝用户“ $user”@‘ localhost’的访问(使用密码: YES)

如何使 bash 文件作为命令行运行?

153234 次浏览

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.

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

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