Skip to content

Instantly share code, notes, and snippets.

@DILL44 DILL44/adddbuser
Last active Aug 29, 2015

Embed
What would you like to do?
#!/bin/bash
read -s -p "Enter root DB Password: " PASSDB
echo ""
read -s -p "Enter new DB Password: " PASSWORD
echo ""
read -s "Enter website server host: " HOST
echo ""
EXPECTED_ARGS=2
E_BADARGS=65
NAME_DB=$2
NAME_USER=$1
ERROR=''
LISTDB=''
CONNECTDB="mysql -h localhost -u root -p${PASSDB} -B -N -e"
#test username
while read User; do
if [[ "$NAME_USER" == "$User" ]]; then
ERROR="${ERROR}user $NAME_USER exist \n"
break
fi
done < <($CONNECTDB 'USE mysql; SELECT `User` FROM `user`;')
#test db
while read db; do
#$LISTDB="${LISTDB} db"
if [[ "$NAME_DB" == "$db" ]]; then
ERROR="${ERROR}database $NAME_DB exist"
break
fi
done < <($CONNECTDB 'SHOW DATABASES;')
#create user and db
if [[ $ERROR == '' ]]
then
Q1="CREATE DATABASE IF NOT EXISTS ${NAME_DB};"
Q2="GRANT USAGE ON *.* TO ${NAME_USER}@${HOST} ;"
Q3="GRANT ALL ON ${NAME_DB}.* TO ${NAME_USER}@${HOST} IDENTIFIED BY '${PASSWORD}';"
Q6="FLUSH PRIVILEGES;"
SQL="${Q1}${Q2}${Q3}${Q4}"
if [ $# -ne $EXPECTED_ARGS ]
then
echo "Usage: $0 dbuser dbname"
exit $E_BADARGS
fi
$CONNECTDB "$SQL"
#echo $SQL
else
echo -e $ERROR
fi
#thank you to Rob Scnkhmitt http://www.bluepiccadilly.com/2011/12/creating-mysql-database-and-user-command-line-and-bash-script-automate-process and http://twitter.com/rob_schmitt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.