Skip to content

Instantly share code, notes, and snippets.

@idimopoulos
Forked from ainsofs/drupal mysql commands
Last active September 17, 2017 11:49
Show Gist options
  • Save idimopoulos/2885fecd3ed63ccd4ce1a2985ddf34cf to your computer and use it in GitHub Desktop.
Save idimopoulos/2885fecd3ed63ccd4ce1a2985ddf34cf to your computer and use it in GitHub Desktop.
Usefull scripts
#!/bin/bash
# Creates a database and a user and grants all previleges
# to the user. The name of the database, the user and the
# password are all passed as the first argument in the
# script.
# In order to run the script below, the root user must
# be able to login without password or the password
# must be set in the ~/.my.cnf file of the user that
# runs the script.
# @see: http://serverfault.com/a/143587
if [ $# -eq 0 ]; then
echo "Please, provide the name of the user/password/database as the first parameter."
exit -1;
fi
# Check if database exists and if not, create it.
DATABASE_EXISTS=`mysql -uroot --batch -e "SHOW DATABASES LIKE '$1';" | grep "$1" > /dev/null; echo "$?"`;
if [ $DATABASE_EXISTS -eq 0 ]; then
echo "Database already exists. Will not re-create it."
else
mysql -uroot -e "CREATE DATABASE IF NOT EXISTS $1;"
echo "Database '$1' created."
fi
USER_EXISTS=`mysql -uroot -B -N -e "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '$1' AND host = 'localhost')"`
if [ $USER_EXISTS -eq 1 ]; then
# Delete user using 'mysql -uroot -e \"DROP USER '$1'@'localhost';\"'"
echo "User already exists. Moving on to set the privileges."
else
mysql -uroot -e "CREATE USER '$1'@'localhost' IDENTIFIED BY '$1';"
echo "User '$1'(localhost) created with password '$1'.";
fi
# Grant privileges.
mysql -uroot -e "GRANT ALL PRIVILEGES ON $1.* TO '$1'@'localhost';"
echo "Full privileges set on user '$1' to the '$1' database."
# Reload privileges.
mysql -uroot -e "FLUSH PRIVILEGES;"
echo "Privileges reloaded."
echo "All set."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment