Skip to content

Instantly share code, notes, and snippets.

@DILL44
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DILL44/10387776 to your computer and use it in GitHub Desktop.
Save DILL44/10387776 to your computer and use it in GitHub Desktop.
#!/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