unix 如何在bash上运行MySQL命令?

kpbpu008  于 12个月前  发布在  Unix
关注(0)|答案(3)|浏览(133)

下面的代码在命令行上工作

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文件像命令行一样运行?

xiozqbni

xiozqbni1#

要在bash中扩展变量,请使用双引号(即"),参见SC2016,例如:

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

字符串

eh57zj3b

eh57zj3b2#

这一个工作,双引号时,$user和$password是外面的单引号。单引号时,在一个单引号语句。

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

字符串

wi3ka0sx

wi3ka0sx3#

我写了一个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

字符串

相关问题