简体   繁体   中英

How to grant MySQL privileges in a bash script?

I need to grant privileges to a database from within a bash script. Some parameters are in the form of variables, say, the username and the password. The command in a mysql shell would look like this:

GRANT ALL ON *.* TO "$user"@localhost IDENTIFIED BY "$password";

...Except that $user and $password would be replaced by their values.

Is there a way to perform such a command from within a bash script?

Thank you!

There you go :)

#!/bin/bash

MYSQL=`which mysql`
EXPECTED_ARGS=3

Q1="USE $1;"
Q2="GRANT ALL ON *.* TO '$1'@'localhost' IDENTIFIED BY '$2';"
Q3="FLUSH PRIVILEGES;"
SQL="${Q1}${Q2}${Q3}"

if [ $# -ne $EXPECTED_ARGS ]
then
  echo "Usage: $0 dbname dbuser dbpass"
  exit $E_BADARGS
fi

$MYSQL -uroot -p -e "$SQL"

If we don´t know the password we can get it with:

cat /etc/psa/.psa.shadow

So we can get into mysql without prompt password like:

mysql -uadmin -p`cat /etc/psa/.psa.shadow`

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