Skip to content

Instantly share code, notes, and snippets.

@shoaibi
Created June 25, 2015 15:45
Show Gist options
  • Select an option

  • Save shoaibi/6416a3c83c5f3f49398f to your computer and use it in GitHub Desktop.

Select an option

Save shoaibi/6416a3c83c5f3f49398f to your computer and use it in GitHub Desktop.
Create a database and user
#!/bin/bash
#
# While working with webapps I found myself creating the database credentials
# as well as the databases over and over. For me the username to connect to
# database was always same as the database name, almost always. So I created
# the following script to help me quickly setup the credentials
#
# Ways you can use it:
# $0 secret
# In this case database's name, user's name and password
# would all be set to 'secret' (without quotes)
#
# $0 dbname secret
# In this case database's name, user's name would be set to 'dbname'
# and password would be set to 'secret' (without quotes)
#
# $0 dbname uname pwdhere
# In this case database's name would be 'dbname
# user's name would be 'uname and password would be
# set to 'pwdhere' (without quotes)
E_BADARGS=65
MYSQL=`which mysql`
database_name="$1"
database_user="$database_name"
database_password="${@: -1}"
if [ $# -eq 3 ]; then
database_user="$2"
elif [ $# -lt 1 -o $# -gt 3 ]; then
echo "Usage: $0 dbname dbuser dbpass"
echo " OR "
echo "Usage: $0 dbuser dbpass"
echo " Here dbname would be assumed to be same as dbuser"
echo " OR "
echo "Usage: $0 dbuser"
echo " Here dbname and dbpass would be assumed to be same as dbuser"
exit $E_BADARGS
fi
Q1="CREATE DATABASE IF NOT EXISTS $database_name;"
Q2="GRANT ALL ON *.* TO '$database_user'@'localhost' IDENTIFIED BY '$database_password';"
Q3="FLUSH PRIVILEGES;"
SQL="${Q1}${Q2}${Q3}"
echo $MYSQL -e "$SQL"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment