How to run mysql command on bash?

后端 未结 3 1410
南方客
南方客 2021-02-01 00:15

The following code works on the command line

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


        
相关标签:
3条回答
  • 2021-02-01 00:48

    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
    
    0 讨论(0)
  • 2021-02-01 01:01

    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';'
    
    0 讨论(0)
  • 2021-02-01 01:06

    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.

    0 讨论(0)
提交回复
热议问题