如何在bash上运行mysql命令?


72

以下代码在命令行上有效

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'的访问被拒绝(使用密码:是)

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

Answers:


124

使用BASH变量时,请使用双引号。

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

BASH不会在单引号中扩展变量。


10

当$ user和$ password在单引号之外时,该选项可以使用双引号。在单引号语句中的单引号。

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

2

我写了一个shell脚本,它将从属性文件中读取数据,然后在shell脚本上运行mysql脚本。分享这可能对其他人有帮助。

#!/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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.