Last Updated on January 29, 2023 by Vikash Ekka
Here is a Bash script that can be used to create a new MySQL database:
#!/bin/bash
# Set the database name and credentials
db_name="mydb"
username="myuser"
password="mypassword"
# 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;"
You will need to replace the variables db_name
, username
, and password
with the desired values for your new database.
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.
Please let me know if you have any other questions or need further assistance.