Created
November 4, 2022 09:57
-
-
Save Kehet/315ed5c8013dcbb5d39499fe4301f380 to your computer and use it in GitHub Desktop.
This file contains 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
#!/usr/bin/env sh | |
print_help() { | |
printf '%s\n' "This script generates mysql user and default database for this user" | |
printf 'Usage: %s <username> [<password>]\n' "$0" | |
printf '\t%s\n' "<username>: username and database name" | |
printf '\t%s\n' "<password>: password for user (default: generates random password using pwgen)" | |
} | |
die() { | |
_ret="${2:-1}" | |
printf '\nERROR: %s\n\n' "$1" >&2 | |
print_help >&2 | |
exit "${_ret}" | |
} | |
[ $# -ge 1 ] || die "Not enough arguments given" 1 | |
[ $# -le 2 ] || die "Too many arguments given" 1 | |
USERNAME="$1" | |
PASSWORD="$2" | |
if [ $# -eq 1 ]; then | |
if ! command -v pwgen >/dev/null 2>&1; then | |
die "pwgen not in \$PATH" 2 | |
fi | |
PASSWORD="$(pwgen 25 1)" | |
fi | |
DATABASE="$(echo "$USERNAME" | sed -e 's/[^a-zA-Z0-9]/_/g')" | |
mysql -u root -p <<SQL | |
CREATE DATABASE ${DATABASE} /*\!40100 DEFAULT CHARACTER SET utf8 */; | |
CREATE USER '${DATABASE}'@'%' IDENTIFIED BY '${PASSWORD}'; | |
GRANT ALL PRIVILEGES ON ${DATABASE}.* TO '${DATABASE}'@'%'; | |
FLUSH PRIVILEGES; | |
SQL | |
printf "\nCreated user %s with database %s and password %s\n\n" "${USERNAME}" "${DATABASE}" "${PASSWORD}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment