MySQL Database and User Create bash script v2

Usage:

  • Run the script as usual: ./create-db.sh [user] [database_name]
  • When prompted, enter the MySQL root password. The input will not be displayed for security.
./create-db.sh [user] [database_name]
#!/bin/bash

# Check if the correct number of arguments is given
if [ "$#" -ne 2 ]; then
    echo "Usage: $0 [username] [database_name]"
    exit 1
fi

# Assign arguments to variables
USERNAME=$1
DATABASE=$2

# Prompt for MySQL root password
echo -n "Enter MySQL root password: "
read -s MYSQL_ROOT_PASSWORD
echo

# Prompt for MySQL user password
echo -n "Enter password for MySQL user '${USERNAME}': "
read -s MYSQL_USER_PASSWORD
echo

# MySQL root user (assuming 'root')
MYSQL_ROOT_USER='root'

# Command to create a new database
CREATE_DATABASE="CREATE DATABASE IF NOT EXISTS ${DATABASE};"

# Command to create a new user with the provided password on the new database
CREATE_USER="CREATE USER IF NOT EXISTS '${USERNAME}'@'localhost' IDENTIFIED BY '${MYSQL_USER_PASSWORD}';"
GRANT_PRIVILEGES="GRANT ALL PRIVILEGES ON ${DATABASE}.* TO '${USERNAME}'@'localhost';"
FLUSH_PRIVILEGES="FLUSH PRIVILEGES;"

# Execute the commands
mysql -u"${MYSQL_ROOT_USER}" -p"${MYSQL_ROOT_PASSWORD}" -e "${CREATE_DATABASE}${CREATE_USER}${GRANT_PRIVILEGES}${FLUSH_PRIVILEGES}"

echo "Database and user created successfully."

Here are the steps to make your create-db.sh script globally accessible:

sudo mv create-db.sh /usr/local/bin
sudo chmod +x /usr/local/bin/create-db.sh

Optional: Rename the Script for Easier Access:

If you want, you can rename the script to just create-db for ease of use:

sudo mv /usr/local/bin/create-db.sh /usr/local/bin/create-db

Views: 189