Скрипт добавления базы и пользователя MySQL

Простой bash скрипт, добавляющий базу и одноименного пользователя с указанным вами паролем.

#!/bin/bash
# Script created by UbuntuClub.org (c) 2019

echo "Adding new MySQL database and user"

SUDO=''
if (( $EUID != 0 )); then
    SUDO='sudo'
fi

echo "Please enter new database user name: "
read MAINDB

# replace "-" with "_" for database username
MAINDB=${MAINDB//[^a-zA-Z0-9]/_}

echo "Please enter new database user password: "
read -s PASSWDDB

# If /root/.my.cnf exists then it won't ask for root password
if [ -f /root/.my.cnf ]; then
    mysql -e "CREATE DATABASE ${MAINDB} /*\!40100 DEFAULT CHARACTER SET utf8 */;"
    mysql -e "CREATE USER ${MAINDB}@localhost IDENTIFIED BY '${PASSWDDB}';"
    mysql -e "GRANT ALL PRIVILEGES ON ${MAINDB}.* TO '${MAINDB}'@'localhost';"
    mysql -e "FLUSH PRIVILEGES;"

# If /root/.my.cnf doesn't exist then it'll ask for root password   
else
    ${SUDO} mysql -uroot -e "CREATE DATABASE ${MAINDB} /*\!40100 DEFAULT CHARACTER SET utf8 */;"
    ${SUDO} mysql -uroot -e "CREATE USER ${MAINDB}@localhost IDENTIFIED BY '${PASSWDDB}';"
    ${SUDO} mysql -uroot -e "GRANT ALL PRIVILEGES ON ${MAINDB}.* TO '${MAINDB}'@'localhost';"
    ${SUDO} mysql -uroot -e "FLUSH PRIVILEGES;"
fi

echo ""
echo "Created database '${MAINDB}' for user '${MAINDB}'."
echo "Done."
echo ""
on mysql, mariadb, percona, ubuntu