Created
October 27, 2015 17:05
-
-
Save wicochandra/16a9ab122ce0cf7fdddc to your computer and use it in GitHub Desktop.
Bash script to create new database and user
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! /bin/bash | |
| databaseName="$1" | |
| rootUser="root" | |
| rootPass="pass" | |
| user=$databaseName | |
| userPassword=$(date +%s | sha256sum | base64 | head -c 15 ; echo) | |
| runMySql() { | |
| echo $(/usr/bin/mysql -u$rootUser -p$rootPass -e "$1;" 2>&1) | |
| } | |
| if [ ! -n $databaseName ]; then | |
| echo "ERROR: Please Enter Database Name" | |
| exit 1 | |
| fi | |
| createDBLog=$(runMySql "CREATE DATABASE $databaseName") | |
| if [[ $createDBLog == *"ERROR"* ]]; then | |
| if [ "$2" != '--force' ]; then | |
| echo "ERROR ${createDBLog##*ERROR}" | |
| exit 2 | |
| fi | |
| fi | |
| createUserLog=$(runMySql "CREATE USER '$user'@'localhost' IDENTIFIED BY '$userPassword';GRANT ALL PRIVILEGES ON $databaseName.* TO '$user'@'localhost' WITH GRANT OPTION") | |
| if [[ $createUserLog == *"ERROR"* ]]; then | |
| if [ "$2" != '--force' ]; then | |
| echo "ERROR ${createUserLog##*ERROR}" | |
| exit 3 | |
| fi | |
| fi | |
| changePasswordLog=$(/usr/bin/mysql -u$rootUser -p$rootPass -e "SET PASSWORD FOR '$user'@'localhost' = PASSWORD('$userPassword');" 2>&1) | |
| if [[ $changePasswordLog == *"ERROR"* ]]; then | |
| echo "ERROR ${changePasswordLog##*ERROR}" | |
| exit 4 | |
| fi | |
| echo "Name = $databaseName" | |
| echo "User = $user" | |
| echo "Pass = $userPassword" | |
| exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment