Skip to content

Instantly share code, notes, and snippets.

@huyby
Last active August 29, 2015 14:23
Show Gist options
  • Save huyby/3d02396d88aedf4f2ef3 to your computer and use it in GitHub Desktop.
Save huyby/3d02396d88aedf4f2ef3 to your computer and use it in GitHub Desktop.
Create a MySQL database, dito user and random generated password.
#!/bin/sh
# Tiny script to create a mysql user and database with same
# name. A random password is generated (yay!)
usage() {
cat << __EOT
Usage: createmysqldb.sh <dbname>
where <dbname> is the one-word name you'd like to use as database name and
username if -u parameter is not set.
Options:
-u <username>: set a username different from the dbname
-p <password>: set a custom password, if not set a random password is generated
__EOT
exit 1
}
MYSQL=`which mysql`
if [ -z $MYSQL ]; then
cat << __EOT
Error: there was no 'mysql' executable found.
If you have MySQL installed you have to make a symbolic link in '/usr/local/bin'
to the 'mysql' program located in the MySQL installation directory.
e.g. $ ln -s /usr/local/mysql5.1.49/bin/mysql /usr/local/bin/mysql
__EOT
exit 1
fi
PASSWORD=
USERNAME=
while getopts "u:p:" OPTION
do
case $OPTION in
u)
USERNAME=$OPTARG
;;
p)
PASSWORD=$OPTARG
;;
?)
usage
;;
esac
done
shift $(($OPTIND - 1))
if [ -z $1 ]; then
usage
fi
if [ -z $PASSWORD ]; then
PASSWORD=`openssl rand -base64 16 | tr -d "="`
fi
if [ -z $USERNAME ]; then
USERNAME=$1
fi
if [ ${#USERNAME} -gt 16 ]; then
echo "Username is too long: ${#USERNAME} characters, limit is 16"
exit 1
fi
Q1="CREATE USER '$USERNAME'@'localhost' IDENTIFIED BY '$PASSWORD';"
Q2="GRANT USAGE ON *.* TO '$USERNAME'@'localhost' IDENTIFIED BY '$PASSWORD';"
Q3="CREATE DATABASE IF NOT EXISTS \`$1\` CHARACTER SET utf8 COLLATE utf8_general_ci;"
Q4="GRANT ALL PRIVILEGES ON \`$1\` . * TO '$USERNAME'@'localhost';"
Q5="FLUSH PRIVILEGES;"
SQL="${Q1}${Q2}${Q3}${Q4}${Q5}"
$MYSQL -u root -p -e "$SQL"
if [ $? -eq 0 ]; then
cat << __EOT
Created database $1
Generated user "$USERNAME" with following password: "$PASSWORD"
__EOT
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment