Skip to content

Instantly share code, notes, and snippets.

@thejsj
Created October 24, 2013 21:44
Show Gist options
  • Save thejsj/7145580 to your computer and use it in GitHub Desktop.
Save thejsj/7145580 to your computer and use it in GitHub Desktop.
Bash script to automatically create MySQL databases where the database name and the username are the same. First argument: database name/username. Second argument: mysql_user password.
#!/bin/bash
params=" -uroot -p"
echo ' - - - - - - - '
echo 'DB Name : '$1
echo 'Password: '$2
# Create Database
echo ' - - - - - - - '
echo 'CREATE DATABASE IF NOT EXISTS $1;'
# Grant Options (Creates User Automatically)
echo ' - - - - - - - '
echo "GRANT ALL PRIVILEGES ON $1.*
TO '$1'@'%' IDENTIFIED BY '$2'
WITH GRANT OPTION;"
read -p "Do you wish to install this program? [Y/N] : " yn
if [ $yn = "y" -o $yn = "Y" ]; then
# Create Database
mysql $params <<DELIMITER
CREATE DATABASE IF NOT EXISTS $1;
DELIMITER
# Grant Options (Creates User Automatically)
# http://stackoverflow.com/questions/4528393/mysql-create-user-only-when-the-user-doesnt-exist
mysql $params <<DELIMITER
GRANT ALL PRIVILEGES ON $1.*
TO '$1'@'%' IDENTIFIED BY '$2'
WITH GRANT OPTION;
DELIMITER
mysql $params <<DELIMITER
GRANT ALL PRIVILEGES ON $1.*
TO '$1'@'localhost' IDENTIFIED BY '$2'
WITH GRANT OPTION;
DELIMITER
mysql $params <<DELIMITER
GRANT ALL PRIVILEGES ON $1.*
TO '$1'@'127.0.0.1' IDENTIFIED BY '$2'
WITH GRANT OPTION;
DELIMITER
fi
@mmasko
Copy link

mmasko commented Dec 24, 2018

brilliant.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment