Shell Script to Create and Grant Privilege to a new user

#!/bin/bash
#Script to Create a user and assign privilege to a MySQL Database
read  -p  "Please Enter Database Name:" dbname
mysql -Bse "USE $dbname" 2> /dev/null

if [ $? -eq 0 ]; then

        read -p "Please enter the  username you wish to create : " username

        read -p "Please Enter Host To Allow Access Eg: %,ip or hostname : " host

        read -p "Please Enter the Password for New User ($username) : " password

        query="GRANT ALL PRIVILEGES ON $dbname.* TO $username@'$host' IDENTIFIED BY 
        '$password'";

        read -p "Executing Query : $query , Please Confirm (y/n) : " confirm

        if [ "$confirm" == 'y' ]; then
                mysql -e "$query"
                mysql -e "flush privileges"
        else
                read -p "Aborted, Press any key to continue.."
        fi
else
        echo "The Database: $dbname doesnot exist, please specify a database that exists";
fi

You may also like...