Skip to content

Instantly share code, notes, and snippets.

@nateflink
Last active December 18, 2015 12:49
Show Gist options
  • Save nateflink/5785237 to your computer and use it in GitHub Desktop.
Save nateflink/5785237 to your computer and use it in GitHub Desktop.
A bash script that adds a mysql user, and creates a database with the same name as the user and echos the generated password
#!/bin/bash
#By Nate Flink
# Adds a mysql user, and creates a database with the same name as the user and echos the generated password
if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ]; then
echo "Usage: ./$0 [mysql db username] [mysql user password] [new identifier] [optional password]"
exit 1
fi
DB_PASSWORD=$(env LC_CTYPE=C tr -dc "a-zA-Z0-9-_\$\?" < /dev/urandom | head -c 16)
DB_USER=$3
if [ -n "$4" ]; then
DB_PASSWORD=$4
fi
#sql for creating a user and a database
CMD=$(cat <<EOF
CREATE USER '$DB_USER'@'%' IDENTIFIED BY '$DB_PASSWORD';
GRANT USAGE ON * . * TO '$DB_USER'@'%' IDENTIFIED BY '$DB_PASSWORD' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;
CREATE DATABASE IF NOT EXISTS \`$DB_USER\`;
GRANT ALL PRIVILEGES ON \`$DB_USER\` . * TO '$DB_USER'@'%';
EOF
)
mysql -u "$1" -p"$2" -e "$CMD"
echo "$DB_PASSWORD"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment