Skip to content

Instantly share code, notes, and snippets.

@GabrielGil
Last active August 29, 2015 14:07
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 GabrielGil/ff8d4e8a09d1e6587b00 to your computer and use it in GitHub Desktop.
Save GabrielGil/ff8d4e8a09d1e6587b00 to your computer and use it in GitHub Desktop.
Bash recipe for MySQL creating user and database with privileges
#!/bin/bash
# CONNECTION to MySQL
DB_CON_USER=""
DB_CON_PASS=""
# THIS is what we want to create.
# @see http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
DB_NAME="" # Max. length. [1-9] (For unquoted)
DB_USER="" # Max. length. [1-9] (For unquoted)
DB_PASS=$(date +%s | sha256sum | base64 | head -c 12)
# CREATE DATABASE
echo "Databases BEFORE doing anything:"
echo "------------------------------------"
mysql -u $DB_CON_USER -p$DB_CON_PASS -e "SHOW DATABASES"
echo "------------------------------------"
echo ""
echo "Creating DB $DB_NAME..."
mysql -u $DB_CON_USER -p$DB_CON_PASS -e "CREATE DATABASE $DB_NAME"
echo ""
echo "Databases AFTER creation:"
echo "------------------------------------"
mysql -u $DB_CON_USER -p$DB_CON_PASS -e "SHOW DATABASES"
echo "------------------------------------"
echo ""
# CREATE USER
echo "USERS table BEFORE creation:"
echo "------------------------------------"
mysql -u $DB_CON_USER -p$DB_CON_PASS -e "SELECT User FROM mysql.user"
echo "------------------------------------"
echo ""
echo "Creating USER $DB_USER..."
mysql -u $DB_CON_USER -p$DB_CON_PASS -e "CREATE USER $DB_USER"
echo ""
echo "USERS table AFTER creation:"
echo "------------------------------------"
mysql -u $DB_CON_USER -p$DB_CON_PASS -e "SELECT User FROM mysql.user"
echo "------------------------------------"
echo ""
echo "Setting password for $DB_USER..."
mysql -u $DB_CON_USER -p$DB_CON_PASS -e "SET PASSWORD FOR $DB_USER= PASSWORD('$DB_PASS')"
# PRIVILEGES
echo "Set PRIVILEGES for $DB_USER"
mysql -u $DB_CON_USER -p$DB_CON_PASS -e "GRANT ALL PRIVILEGES ON $DB_NAME.* TO $DB_USER IDENTIFIED BY '$DB_PASS'"
mysql -u $DB_CON_USER -p$DB_CON_PASS -e "FLUSH PRIVILEGES"
echo "Your DETAILS:"
echo "------------------------------------"
echo "Database : $DB_NAME"
echo "Username : $DB_USER"
echo "Password : $DB_PASS"
echo "------------------------------------"
echo "Done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment