Last Updated on January 29, 2023 by Vikash Ekka
Here is a Bash script that can be used to create a new MySQL database by taking the input from the terminal:
#!/bin/bash
# Prompt for the database name and credentials
read -p "Enter the database name: " db_name
read -p "Enter the username: " username
read -sp "Enter the password: " password
echo
# Connect to MySQL
mysql -u root -p -e "CREATE DATABASE ${db_name};"
# Create a new user
mysql -u root -p -e "GRANT ALL PRIVILEGES ON ${db_name}.* TO '${username}'@'localhost' IDENTIFIED BY '${password}';"
# Flush privileges
mysql -u root -p -e "FLUSH PRIVILEGES;"
This script will prompt the user to enter the desired values for the database name, username and password. The read -sp
command is used to read the password without displaying it on the screen.
This script will:
- Connect to MySQL with the
root
user - Create a new database with the name specified in the
db_name
variable - Create a new user with the name and password specified in the
username
andpassword
variables, and grant all privileges on the new database to that user - Flush the privileges to make sure the new user has access to the new database
You’ll need to have MySQL installed and running on your machine, and you’ll also need to have the mysql
command-line client available in your path.
You can also add further functionality to the script such as checking if the database already exists or not before creating a new one, also you can add a function to import a dump file to the created database and more.