简体   繁体   中英

mysql how to make a query through bash script

How to make a mysql statement or query through bash script?? for example create a user and a database?? i'm trying through a bash script to run a simple mysql statement


echo "insert database name"
read $db
echo "insert username "
read varname
echo "insert password for the user "
read -s varpass

sudo mysql -u root  -e <<EOF
CREATE DATABASE $db;
CREATE USER '$varname'@'localhost' IDENTIFIED BY '$varpass';
GRANT ALL ON $db.* TO '$varname'@'localhost' IDENTIFIED BY '$varpass' WITH GRANT OPTION;
FLUSH PRIVILEGES;
EXIT;
EOF

You can try this.

test.sh

#!/bin/bash

echo "insert database name"
read db
echo "insert username "
read varname
echo "insert password for the user "
read -s varpass

sudo mysql -u root mysql<<EOF
CREATE DATABASE $db;
CREATE USER '$varname'@'localhost' IDENTIFIED BY '$varpass';
GRANT ALL ON $db.* TO '$varname'@'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;
\q
EOF

Note the changes:

  • read $db was changed to read db - the $ was removed
  • Database name was added before <<EOF
  • Exit was replaced with \\q

What if your database had a password

You could create a file ~/.my.cnf with the following contents:

[client]
user=root
password=YourPassword123!!

Then, you can log on to mysql's mysql database using the command mysql mysql . Using that, you can change just the <<EOF line to:

mysql mysql<<EOF

Everything else can remain the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM